stack application

合集下载

Computer-Networks(计算机网络课件)

Computer-Networks(计算机网络课件)
• transport: process-process data transfer
– TCP, UDP
• network: routing of datagrams from source to destination
– IP, routing protocols
• link: data transfer between neighboring network elements
2021/6/7
8
Application Layer
Our goals
• Conceptual, implementation aspects of network application protocols
• transport-layer service models
• client-server paradigm
Functions: 1. Encapsulation 2. Fragmentation and reassembly 3. Connection control 4. Ordered delivery 5. Flow control 6. Error control 7. Addressing 8. Multiplexing 9. Transmission services
2021/6/7
5
Protocol Functions
• Small set of functions that form basis of all protocols
• Not all protocols have all functions
– May have same type of function in protocols at different levels

Developing PowerPC Embedded Application Binary Interface (EABI) Compliant Programs

Developing PowerPC Embedded Application Binary Interface (EABI) Compliant Programs

3.Data Types and AlignmentT he PowerPC architecture defines scalar (integer) data type sizes as shown in Table 1.Table 1 - PowerPC scalar data typesD ata type S ize (bytes)B yte1H alfword2W ord4D oubleword8Q uadword16A ll data types are aligned in memory, and in the stack frame, on addresses that are a multiple of their size. For example, a word, since its size is 4 bytes, is aligned on an address evenly divisible by 4. The address of a halfword is evenly divisible by 2. An exception to this rule is quad-words when they are not contained in a union or structure; they only require alignment to eight byte boundaries. Arrays are aligned on the boundary required by the size of the data type of the array elements.A structure (or union) is aligned based on the alignment requirements of the structures largest member. Thus, if the structure contains a doubleword, the doubleword member must begin on an address evenly divisible by 8. Padding of prior and subsequent members is done as needed to maintain their individual alignment requirements. The size of a structure is always a multiple of the structure's alignment. If necessary a structure is padded after the last member to increase its size to be a multiple of its alignment. EABI compliant compilers and assemblers will automatically create correctly aligned data allocations but the padding required may cause problems for some applications. An example would be a networking- protocol data packet, which has specific alignment requirements. For these situations some compilers allow the alignment feature to be turned off, or overridden with different boundary values. For example, the IBM HighC/C++ compiler has a #pack pragma for this purpose. Since non-aligned data access requires multiple bus cycles for reads and writes, and perhaps even software assistance through an exception handler, performance will be decreased. Non-aligned data access should be avoided if at all possible.T able 2 shows the ANSI C language data types and their sizes. For all types, NULL is defined as the value zero. Signed and unsigned integer types have the same size in all cases.Table 2 - PowerPC ANSI C data typesA NSI C data type P owerPC Data type S ize (bytes)c har b yte1s hort h alfword2i nt w ord4l ong int w ord4e num w ord4p ointer w ord4f loat w ord4d ouble d oubleword8l ong double q uadword164.Register Usage ConventionsT he PowerPC architecture defines 32 general purpose registers (GPRs) and 32 floating-point registers (FPRs). The EABI classifies registers as volatile, nonvolatile, and dedicated. Nonvolatile registers must have their original values preserved, therefore, functions modifying nonvolatile registers must restore theoriginal values before returning to the calling function. Volatile registers do not have to be preserved across function calls.T hree nonvolatile GPR's are dedicated for a specific usage, R1, R2, and R13. R1 is dedicated as the stack frame pointer (SP). R2 is dedicated for use as a base pointer (anchor) for the read-only small data area. R13 is dedicated for use as an anchor for addressing the read-write small data area. Dedicated registers should never be used for any other purpose, not even temporarily, because they may be needed by an exception handler at any time. All the PowerPC registers and their usage are described in Table 3.Table 3 - PowerPC EABI register usageR egister T ype U sed for:R0V olatile L anguage SpecificR1D edicated S tack Pointer (SP)R2D edicated R ead-only small data area anchorR3 - R4V olatile P arameter passing / return valuesR5 - R10V olatile P arameter passingR11 - R12V olatileR13D edicated R ead-write small data area anchorR14 - R31N onvolatileF0V olatile L anguage specificF1V olatile P arameter passing / return valuesF2 - F8V olatile P arameter passingF9 - F13V olatileF14 - F31N onvolatileF ields CR2 - CR4N onvolatileO ther CR fields V olatileO ther registers V olatile5.Stack Frame ConventionsT he PowerPC architecture does not have a push/pop instruction for implementing a stack. The EABI conventions of stack frame creation and usage are defined to support parameter passing, nonvolatile register preservation, local variables, and code debugging. They do this by placing the various data into the stack frame in a consistent manner. Each function which either calls another function or modifies a nonvolatile register must create a stack frame from memory set aside for use as the run-time stack. If a function is a leaf function (meaning it calls no other functions), and does not modify any nonvolatile registers, it does not need to create a stack frame.T he SP always points to the lowest addressed word of the currently executing functions stack frame. Each new frame is created adjacent to the most recently allocated frame in the next available lower addressed memory. The stack frame is created by a function's prologue code and destroyed in its epilogue code. Stack frame creation is done by decrementing the SP just once, in the function prologue, by the total amount of space required by that function. To insure the SP update is an atomic operation that cannot be interrupted, a store-with-update (stwu) instruction is used. The prologue will also save any nonvolatile registers the function uses into the stack frame. Below is an example function prologue.F uncX:mflr%r0; Get Link registers twu%r1,-88(%r1); Save Back chain and move SPs tw%r0,+92(%r1); Save Link registers tmw%r28,+72(%r1); Save 4 non-volatiles r28-r31T he stack frame is removed in the function's epilogue by adding the current stack frame size to the SP before the function returns to the calling function. The epilogue code of a function restores all registers saved by the prologue, de-allocates the current stack frame by incrementing the SP, then returns to the calling function. The following function epilogue example corresponds to the above prologue.l wz%r0,+92(%r1); Get saved Link registerm tlr%r0; Restore Link registerl mw%r28,+72(%r1); Restore non-volatilesa ddi%r1,%r1,88; Remove frame from stackb lr; Return to calling functionF igure 1 illustrates the stack frame concept by using a 2-level deep, function calling example. At time 1, function A exists and calls function B. At 2, B's prologue code has executed and created B's frame. At 3, B has called C and C's prologue code has executed. At 4, function C has terminated and C's epilogue code has destroyed C's frame by incrementing the value in the SP.Figure 1 - Stack Frame creation and destructionThe stack frame is always doubleword aligned (on 8 byte boundaries) by using padding, if necessary. Figure 2 shows the stack frame organization including all optional areas.F PR Save Area(optional, size varies)G PR Save Area(optional, size varies)C R Save Word(optional)L ocal Variables Area(optional, size varies)F unction Parameters Area(optional, size varies)P adding to adjust size to multiple of 8 bytes(optional, size varies 1-7 bytes)L R Save WordB ack Chain WordFigure 2 - EABI Stack FrameA ll stack frames have a header consisting of two fields - the Back Chain Word and the Link Register (LR) Save Word. The Back Chain Word contains the address of the previous frames Back Chain Word field, thereby forming a linked-list of stack frames. The Back Chain Word is always located at the lowestaddress of the stack frame. The LR Save Word is used by functions to store the current value of the Link Register prior to modifying it. The value in the LR upon entry into a subroutine represents the return address to the calling function. It is located in the word immediately above the Back Chain Word field.T he Function Parameter Area is optional and varies in size. It contains additional function arguments when there are to many to fit into the designated registers R3-R10. It is located just above the LR Save Word in the callers stack frame. The Local Variables Area is for functions local variables when there are more than can be contained in the available volatile registers. If a function modifies any of the nonvolatile Condition Register (CR) fields it must save the entire CR in the CR Save Area.T he General Purpose Register (GPR) Save Area is optional and varies in size. When saving any GPR, all the GPRs from the lowest to be saved up through R31, inclusive, are saved. For example, if a function is modifying R17, it must create a stack frame large enough to contain R17 through R31 in its GPR Save Area. The same conventions apply for the Floating point Register Save Area for saving the FPR nonvolatile registers. Code for implementations of the PowerPC that do not have floating-point hardware would not create the FP Save Area as there are no FPRs to save.6.Parameter PassingF or PowerPC processors it is more efficient to pass arguments in registers than using memory. Up to eight scalar values are passed by using R3 through R10 and return values are passed back in R3 and R4. Up to eight arguments of the floating point data type can be passed using F1 to F8 and F1 is used to return a floating-point value. If there are more arguments than can be passed using the registers, space for the additional arguments is allocated for them in the stack frame's Function Parameters Area. Likewise, returned values that will not fit into R3 and R4 (or F1) are also passed by using the Function Parameters Area. The following C code fragment illustrates the concept.#include "stdio.h"v oid func1(int);i nt var1;m ain(){v ar1 = 4;f unc1(var1);}v oid func1(int arg1){p rintf("func1 - arg1 value: %d\n",arg1);}T o implement the C language statements the following assembly language instructions illustrate loading and passing the value in var1 to func1. After var1 is set to 4, R3 is loaded with the value in var1 in order to pass it as an argument. The lwz instruction is used to load R3. Notice that after the instructions to set var1 = 4, R12 contains the high order 16-bits of the address of var1 and is therefore used by the lwz instruction. R3 is used since it is the first available parameter passing register for integer values.v ar1 = 4;l i%r11,4a ddis%r12,%r0,var1@has tw%r11,var1@l(%r12)f unc1(var1);l wz%r3,var1@l(%r12)b l func17.Small Data AreasT he EABI has a construct known as the Small Data Area (SDA) designed to take advantage of the PowerPC base plus displacement addressing mode. The displacement is a signed 16-bit value, therefore a total of 64k (plus or minus a 32K offset) bytes may be addressed without changing the value in a base register. The 16-bit displacement fits, along with the instruction op-code, into a single instruction word. This fact means it is a more memory efficient method of accessing a variable than referencing it by using a full 32-bit address. That's because only one instruction word is required instead of the two needed to access it as a 32-bit address. SDAs are useful for global and static variables and constants.T here are two SDAs, one for read-write variables and a second for read-only variables. The small data areas are referenced by a base register loaded once, when the C runtime environment is initialized. R2 is the base for the read-only (const type) small data area, and R13 is the base for the read-write (non-const type) small data area.V ariables for the R13 based read-write SDA are contained in one of two ELF segments, either .sdata, or .sbss. For initialized read-write variables, .sdata is used and .sbss is used for non-initialized read-write variables. Typically the .sbss variables are given a default initial value of 0 at run-time. Since this SDA is read-write it must be located in RAM.H ere is an example instruction to fetch the value of a read-write small data area variable. It is located at an offset of 32 bytes greater than the anchor value:l wz r29,32(r13)V ariables for the R2 based read-only SDA are contained in one of the segments .sdata2 and .sbss2. For initialized read-only variables, .sdata2 is used. For non-initialized variables, .sbss2 is used. Typically, non-initialized variables are given a default initial value of 0 at run-time. Since the SDA is read-only, it may be located in ROM as long as initialization of the .sbss2 segment contained variables is not required.T he PowerPC architecture treats R0 as a value of zero (not the content of R0) when used as the base register for the base + displacement addressing mode for some instructions. These instructions include the load, store, and various cache management instructions. Therefore, R0 acts as an anchor for a third, implicit, small data area which includes the lowest and highest 32k bytes of the processor memory address space.W ith the IBM HighC/C++ compiler, placement of variables into SDAs is enabled using the pragmaPush_small_data. By default, global variables are not placed into an SDA. The pragma can be invoked by using a compiler option. The option "-Hpragma=Push_small_data(4;0)" instructs that read-write variables that are 4 bytes or less in size should be stored in the read-write SDA. It also instructs that no read-only variables are to be placed into the read-only SDA by specifying the value 0, for the second argument. The following C program fragment will help illustrate the machine instructions used to access a global variable.i nt var1;m ain(){var1 = 4;func1(var1);}B elow are the assembly language instructions generated by the compiler for writing the value 4 to the global variable var1, when it is not in an SDA. Three instructions are required to store a value intovar1.l i%r11,4a ddis%r12,%r0,var1@has tw%r11,var1@l(%r12)1. li gets the value to be set into register R11.2. addis is used to load R12 with the high-order halfword of the address of var1.3. stw uses the base + displacement addressing mode. The displacement, from the base address inR12, is the low halfword of var1's address.W hen in the read-write SDA, the resulting two instructions for writing a value to var1 are: l i%r12,4s tw%r12,var1@sdaxr(%r13)Note that to use any SDAs, you need the C runtime environment creation code to initialize the small data area anchor registers. For the IBM evaluation kit user, you can do this by adding the following code to the ./samples/bootllib.s routine right before the jump to the _kernel_entry routine. The macros _SDA_BASE_ and _SDA2_BASE_ are defined automatically by the linker if the associated SDAs are used. For _SDA_BASE_, the value is the address to which all data in the .sdata and .sbss sections can be addressed using a 16-bit signed offset. If an SDA is not used the associated macro's value will be zero.!**************************************************************************** ! INITIALIZATION OF BASE REGISTERS FOR SMALL DATA AREAS:!**************************************************************************** lis%r2,_SDA2_BASE_@ha! r2 is the read-only SDA anchoraddi%r2,%r2,_SDA2_BASE_@llis%r13,_SDA_BASE_@ha! r13 is the read-write SDA anchora ddi%r13,%r13,_SDA_BASE_@lFor comparison, Table 4 shows the resulting changes in code size and execution speed for a Dhrystone benchmark. The compiler used was the IBM HighC/C++ compiler v3.61 and execution took place on the IBM PowerPC 401GF evaluation board. Row 1 shows the results of using options for pure speed (-O6) and allowing inlining of functions called up to 150 times (-Hic=150) that have fewer than 150 nodes (-Hit=150). Row 2 adds the use of SDAs for any read-write variable whose data type has a size of 8 bytes or fewer, and any read-only variable whose data type size is of 4 bytes or smaller.Compile options dhry_1.o code size dhry_2 code size benchmark result -O6 -Hic=150 -Hit=1502300 bytes572 bytes88KDhry/sec-O6 -Hic=150 -Hit=1501988 bytes552 bytes77kDhry/sec-Hpragma=Push_small_data(8;4)Table 4 - Small data area effects on Dhrystone application8.ConclusionT he EABI provides for vendor independent tool interoperability via the ELF/DWARF file format standards. This allow developers to mix and match various EABI compliant components to create a software development tool chain for their needs. In addition, the EABI standards on register usage and parameter passing also allow independently developed code to be reused without modification.9. ReferencesThe following references are presented in a suggested reading order progressing from a comprehensive overview through the standards documents from most PowerPC specific to most general.•Programming PowerPC Embedded Applications, Embedded Systems Programming magazine, December 1995. Back issue information available from embedded@•PowerPC Embedded Application Binary Interface, Version 1.0, IBM and Motorola, January 10, 1995.Available from ESOFTA at /pdfs/ppceabi.pdf•System V Application Binary Interface, PowerPC Processor Supplement, Sun Microsystems and IBM, September 1995. Available from ESOFTA at /pdfs/SVR4abippc.pdf •System V Application Binary Interface, Third Edition, UNIX Systems Laboratories, 1994•DWARF Debugging Information Format, Revision 1.1.0, UNIX International October 6, 1992.Available from ESOFTA at /pdfs/dwarf.v1.1.0.pdf© International Business Machines Corporation, 1998All Rights Reserved* Indicates a trademark or registered trademark of the International Business Machines Corporation.** All other products and company names are trademarks or registered trademarks of their respective holders.IBM and IBM logo are registered trademarks of the International Business Machines Corporation.IBM will continue to enhance products and services as new technologies emerge. Therefore, IBM reserves the right to make changes to its products, other product information, and this publication without prior notice. Please contact your local IBM Microelectronics representative on specific standard configurations and options.IBM assumes no responsibility or liability for any use of the information contained herein. Nothing in this document shall operate as an express or implied license or indemnity under the intellectual property rights of IBM or third parties. NO WARRANTIES OF ANY KIND, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ARE OFFERED IN THIS DOCUMENT.。

HCIPOpenStack实验环境搭建指南

HCIPOpenStack实验环境搭建指南

HCIPOpenStack实验环境搭建指南华为认证CLOUD系列教程HCIP-Cloud Computing-OpenStack 实验环境搭建指南1前言简介本指南的目的在于指导地区部、供应商、HALP购买设备、安装实验环境以及实验过程中需要用到的软件等,最终组建成拓扑图,基于HCIP-Cloud Computing-OpenStack实验手册完成HCIP-Cloud Computing-OpenStack的相应实验。

实验环境说明本实验环境面向准备HCIP-Cloud Computing-OpenStack考试的OpenStack运维工程师。

本实验环境搭建指南以一台服务器安装一套OpenStack实验环镜为例进行介绍,每套实验环境适用于一名学员同时上机操作。

参考本实验环境搭建指南的“附录1:安装并使用多套OpenStack实验环境”可在一台服务器上安装并使用多套OpenStack实验环镜。

注:若使用个人PC搭建OpenStack实验环境,请关注后续华为认证官网发布的《HCIP-Cloud Computing-OpenStack V1.0实验环境搭建指南(PC 版)》。

设备介绍HCIP-Cloud Computing-OpenStack实验需服务器以及相关软件,推荐要求如下:实验拓扑组网说明本实验环境在服务器上安装Ubuntu操作系统,并在Ubuntu上安装VirtualBox软件。

通过自动化安装脚本在VirtualBox中部署OpenStack实验环境。

每套OpenStack实验环境包括一个Controller节点和一个Compute节点。

实验环境搭建流程图目录前言 (1)简介 (1)实验环境说明 (1)实验环境搭建 (3)1 BIOS开启虚拟化开关 (6)1.1 实验说明 (6)1.2 前提条件 (6)1.3 操作步骤 (6)2 安装Ubuntu操作系统 (11)2.1 前提条件 (11)2.2 操作步骤 (11)3 安装VirtualBox (18)3.1 前提条件 (18)3.2 操作步骤 (18)4 安装SSH,拷贝文件 (21)4.1 实验说明 (21)4.2 操作步骤 (21)5 (可选)安装远程登录工具 (28)5.1 实验说明 (28)5.2 操作步骤 (28)6 安装OpenStack实验环境 (36)6.1 实验说明 (36)6.2 前提条件 (36)6.3 操作步骤 (36)附录1:安装并使用多套OpenStack实验环境 (41)实验说明 (41)操作步骤 (41)1 BIOS开启虚拟化开关1.1 实验说明开始安装OpenStack环境安装前,需要先在服务器BIOS中开启支持虚拟化开关,否则后续运行OpenStack自动化安装脚本将出现报错提示。

zstack按键程序分析

zstack按键程序分析

本文来自飞比论坛,作者:xingqing帖子地址:/bbs/viewthread.php?tid=393膜拜大作,虚心学习。

看了outm an的关于Rem oTI的教程,受益匪浅,然后找了下以前学习所做的笔记,共享出来,大家共同学习,如果有哪里理解错误请大家给我指出来:Rem oTI遥控板子上按键的发射程序,整个流程及其相对应的程序我都贴上了,好了,首先上个图:很不幸的是,从刚开始分析我就没留意这个图,造成我花了很长时间来想这个按键的流程,看他的流程,已经很明白了:开始(start),所有的列配置为输出,所有的行配置为中断使能输入,这里很简单就是个矩阵键盘,51中是用查询法来检测按键,这里只不过用的是中断方式来触发而已,然后调用消除抖动定时器(start key de-bounce tim er),当定时器溢出的时候,开始扫描按键,如果没有检测到按键,那么有返回到开始之下,重新来,如果有按键被检测到,这时候启动轮询定时器,启动这个定时器的原因是为了能够连发,如果你按下这个键一直不放那么就是靠这个定时器,来实现连发的,连发的时间间隔这个值我们是可以改动的,如果这个时候又检测不到按键了,那么又回到开始之下,当你再次按键的时候是靠中断来触发的。

有很多人觉得读取按键还有无线发送按键命令是在端口0的中断处理函数中进行的,其实不是这样的,中断中只是给这个任务添加了一个定时器而已这里先插一句:分析程序的时候我们要忽略次要的,看主要的。

以上是整个按键的流程了,下面分析下具体的程序:凡是要找个开始,不用说肯定先看主函数,:int m ain(void){/* Initialize hardware 初始化硬件,选择时钟,还有灯的方向选择*/HAL_BOARD_INIT();/* Initialze the HAL driver 初始化板上的硬件*/HalDriverInit();/* Initialize NV system 初始化nv系统????*/osal_nv_init(NULL);/* Initialize MAC 被封掉了 */MAC_InitRf4ce();/* Initialize the operating system 初始化操作系统*/osal_init_system();/* Enable interrupts 使能总中断*/HAL_ENABLE_INTERRUPTS();/* Setup Keyboard callback 这里是选择了按键的检测方式*///最重要的是指向了按键回调函数HalKeyConfig(RSA_KEY_INT_ENABLED, RSA_KeyCbac k);/* Start OSAL 进入操作系统,不能返回 */osal_start_system(); // No Return from herereturn 0;}以上我已经做了注释了,这个主函数很简单,下面看看具体跟按键相关的程序:函数HalDriverInit中,有这么一句/* KEY */#if (defined HAL_KEY) && (HAL_KEY == TRUE)HalKeyInit();#endif我们再看看这个HalKeyInit();函数到底做了什么,void HalKeyInit( void ){#if (HAL_KEY == TRUE)/* Initialize previous key to 0 初始化先前的键值为0*/halKeySavedKeys = HAL_KEY_CODE_NOKEY;//列端口1除了P1_1没有使用之外其他都用到了,设置为普通的IO,方向输出HAL_KEY_COL_SEL &= (uint8) ~HAL_KEY_COL_BITS; // set pin function to GPIOHAL_KEY_COL_DIR |= HAL_KEY_COL_BITS; // set pin direction to output//以下几句是在选择他的触发方式,上升沿触发还是下降沿触发,如果学过单片机的同学//这个应该不是问题if (HAL_KEY_ROW_PULLDOWN)//如果是下拉的话,进来设置所有的引脚为高电平{HAL_KEY_COL_PORT |= HAL_KEY_COL_BITS; // output high on all colum ns}else//如果是上拉,进来设置所有的引脚为低电平{HAL_KEY_COL_PORT &= (uint8) ~HAL_KEY_COL_BITS; // output low on all colum ns }//行端口0设置为普通的IO(所有端口都用到了),方向输入HAL_KEY_ROW_SEL &= ~(HAL_KEY_ROW_BITS); // set pin function to GPIOHAL_KEY_ROW_DIR &= ~(HAL_KEY_ROW_BITS); // set pin direction to input// pull down setup if necessary 如果有必要的话设置为下拉if (HAL_KEY_ROW_PULLDOWN){HAL_KEY_ROW_INP |= HAL_KEY_ROW_PDUPBIT;//设置端口0为下拉}//以下三句程序现在不用管他是做什么用的,后面我们会看到他的作用,/* Initialize callback function 这个要好好关注下,开始的时候这个回调时空的 */pHalKeyProcessFunction = NULL;//这里初始化回调函数是空的/* Start with key is not configured */HalKeyConfigured = FALSE;//起始的时候键值没有被配置halKeyTim erRunning = FALSE;#endif /* HAL_KEY */}上面这个函数只是对按键的初始化,注意这里初始化只是将按键配置成了:普通的IO口,列为输出,行为输入,并没有让行的中断使能,再就是对回调函数的清空,这个回调是重点,要注意!!!!在osal_init_system这个函数中,osalInitTasks这个函数,具体程序如下:void osalInitTasks( void ){uint8 taskID = 0;//注意这里任务ID是从0开始的/*这里返回的是分配内存空间的首地址,注意这个首地址的上一个地址就是他的内存控制头,关于他内存的分配可以看看我的下一教程*/tasksEvents = (uint16 *)osal_m em_alloc( sizeof( uint16 ) * tasksCnt);//分配了足够的空间osal_m em set( tasksEvents, 0, (sizeof( uint16 ) * tasksCnt));//全部初始化为0m acTaskInit( taskID++ ); //添加m ac层的任务被封掉了RCN_Init( taskID++ ); //添加RCN的任务RCN:RF4CE network layer 被封掉了RTI_Init( taskID++ ); //添加RTI的任务R TI:Rem oTI appli cation fram eworkRSA_Init( taskID++ ); //添加RSA的任务Hal_Init( taskID ); //添加硬件抽象层的任务,这里就是对按键处理任务的添加}还有一个数组要十分注意的是:// The order in this table m ust be identi cal to the task initialization calls below in osalInitTask.//这里的顺序很重要,要和osalInitTasks这里添加任务的顺序一样const pTaskEventHandlerFn tasksArr[] ={m acEventLoop,RCN_ProcessEvent,RTI_ProcessEvent,RSA_ProcessEvent,Hal_ProcessEvent};这个数组的顺序和上面的taskID要对应上,也就是说他给每个处理函数排了个队,并且给他们编了个号,而且有个标志位,这个标志位很重要,标志位是靠下层触发的(这句话现在看有点不明白,看到最后的时候你会明白),究竟怎么触发的我们先不用管,还是举个例子吧,比如无线接收到数据了,你要从下层传到上层,最后就是靠下层触发这些标志位,这样上层才知道有事情发生了,通过taskID 找到你相应的函数,这样比较简单,系统在轮询事件的时候是按照这个顺序来走了,你的taskID和相应的程序对不上号那不就乱了吗,简单说下,以后详再说。

stm8 cosmic基本教程

stm8 cosmic基本教程

...
MCD Application
16
关于flash 操作(IAP)
#pragma section (FLASH_CODE) void FlashWrite(void) { ... } void FlashErase(void) { ... } //set back code section to default placement #pragma section ()
From On-chip Peripherals
M外部中断
Filtering Edge Detection Trigger selection Capture Selection Dividing
MCD Application
21
采用输入捕获方式获得外部中断
MCD Application
9
Memory Models>64k (FLASH>32K)
Stack Short (mods) 全局变量默认为是短寻址方式( 全局变量默认为是短寻址方式(位置存放在 小于256的空间 0page) 在变量前 @near 或用指针方式长寻址 Stack Long (modsl) 全局变量默认为是长寻址方式( 全局变量默认为是长寻址方式(位置存放在 大于256的空间) 的空间) 在变量前 @tiny 或用指针方式长寻址 一般来讲,变量放在<256的空间内效率更高
MCD Application
8
Memory Models<64k(FLASH<32K)
Stack Short (mods0) 全局变量默认为是短寻址方式 ( @tiny 存放 在zero page ,8位地址) 位地址) 超出zero page范围须的变量须用 @near定义 Stack Long (modsl0) 全局变量默认为是长寻址方式( 全局变量默认为是长寻址方式( @near 存放 在0x100开始的地址16位空间 ) zero page内定义变量需要加 @tiny 强制定义 一般来讲,变量放在zero page的空间内效率 更高

The.Oreans.(Themida&Winlicense).VM.antidumps-Q

The.Oreans.(Themida&Winlicense).VM.antidumps-Q

The Oreans (Themida/Winlicense) VM antidumps.quosegoOctober 6, 2009 Intro;The virtual machine of any Oreans protected application usually tries to prevent itself from running in any dumped application. It does so with the use of antidumps, these antidumps are small parts of code that try to detect if you’re running a protected application or an unprotected application.This code always resided in the VM making it very hard to analyze. However usually the code checks for values somewhere in memory which get wiped when you dump an application, these checks usually end up in the familiar access violations. However when a value is available, when the application is unprotected, the antidump code will check it against a stored value, if it is not the same it’ll try to disrupt the program. (Quite often successfully.) Another more recent method is the checking of API locations in memory, an API’s location or data is checked against stored values.In this tutorial I will attempt to explain all known antidumps fully. Using new techniques I can now present you all antidumps fully devirtualised. I will however not tell you easy methods to defeat them. That is something you can now do yourself. Please consider the antidumps were first defeated without knowing the actual ASM code, doing it with the info in this tutorial should be easy. General idea of antidumps;Antidumps attempt to detect whether a program dumped or it is run on a different computer.Many things are different between a dumped application and a protected application. The stack is no longer the same, the heap has been wiped and perhaps you’ve changed your PE header. Each of these variables is semi-randomly checked by the Themida VM if they are still the same as defined by the protection. You will notice these antidumps immediately after you dump an application.However some do not show and are only revealed when your dump runs on a different OS, this is due to the checking of API’s. API locations can differ between operating systems and the VM chec ks for such differences when dumped. The locations of these API’s stored by the VM get updated whenever you run the protected application so that they are no problem for protected apps.The SetEvent/StackAntidump;Though there’s already a decent paper o n the stackantidump the SetEvent antidump is not known. However it is very similar to the stackantidump.Stackantidump already differs when dumped, and crashes the program on your computer since the stack will have changed. However the Setevent antidump is more devious and won’t show until you run your dump on a different OS or service pack.As you can see in the following antidump block they are used together to prevent dumping. And both when failing end in the “add dword ptr ss:*esp+,4” and “add esp,8” i nstructions which greatly disrupts the flow of a program. Everything is checked against stored values which can be manipulated.Figure 1: Stackantidump/SetEvent antidump in ASM. As you can see SetEvent and the stack are checked for correctness. Program flow is always destroyed using two instructions.Please note that the location of the SetEvent antidump is not always the SetEvent API in kernel32.dll. It can also be the custom loaded SetEvent in the Oreans kernel32.dll. (Just search for the same bytes as the kernel SetEvent and you’ll end up in the Oreans kernel32. ) As noted in previous tutorials the stackantidump is always the stack address at the entrypoint minus 4. (At least in XP, it differs in Vista as another Oreans expert has pointed out.)Als o the “Custom VM instruction” HLT as shown in this picture can only be executed within VM. The HLT instruction in x86 CPU’s does not function in ring3. The VM executes a custom handler for this instruction which obtains the value of EBP. EBP is used to get data addresses in the form of[EBP+xxxxxxx]. The location of the data location is thusly defined semi dynamically by EBP.This usage of HLT will make Oreans products incompatible with protecting ring0 products that use the x86 version of HLT.The Heap Antidump.Also quite legendary, the heap antidump compares stored values against values located on the heap. These values will have been put there by the packer, and updated when the protection is intact. If the heap is not equal this will fail and the program flow destroyed, if the heap is located in a different memory section it will give an access violation. The effects of this antidump are immediate, after dumping the heap is already different and this antidump will be triggered.The values to be checked by the antidump will be written to the heap as followed.Figure 2: Heap antidump writing in ASM. As you can see the heap is filled with two dwords and the locations are stored to be later checked by the VM.Every time the packer is executed it will write to the heap using ntdll.ReAllocateHeap and these values will be checked within VM, when a program is executed.The following picture will show a heap antidump check. The counter will first be executed and then the heap will be checked. Again this check is simple.Figure 3: Heap antidump in ASM. As you can see the heap is checked for correctness and existence. If it exist and not equal to stored values program flow will be destroyed.Here’s a more direct version of a Heap check;Figure 4: Short heap antidump in ASM. As you can see the heap is checked for correctness and existence. If it exist and not equal to stored values program flow will be destroyed. Note the direct check of the location. The heap antidump location here is stored without encryption in the TM/WL data section and can be modified with ease.The FreeLibrary/SE handler Antidump.Though actually not an antidump but the Check_protection macro. However it is useful to fix, you never know what those developers are using. In essence this macro is just an antidump on speed. Same idea, same checks just different locations.The following picture will show you the full check of this macro. In essence it does not check for protection but for antidump. This makes it defeatable in the same way.Figure 5: The check_protection macro in ASM. As you can see SEH is thoroughly checked for correctness and existence. If it does not it is checked only superficially if it does exist it will be checked more thoroughly and in tandem with the FreeLibrary API.Interestingly it does not have to fail in a dumped application. In theory all checked values here can be identical even on different computers. Though this happens not often, the check_protection macro is not a very solid way to check for the protection.The PE header Antidump.Well in all honesty I could not find a recent implementation of this.. Though I’ve seen quite some variations of this it seems to be no longer in use in recent versions.However I’ll explain the changes Oreans makes in the PE header and which it used to check as antidump. The checks are similar to the previously explained antidumps. However since I am unable to find something that actually uses this I won’t be able to provide an actual checking function.First the normal header;Figure 6: Normal dump of a PE header. As you can see it is valid and except for a few peculiar section names everything looks fine.Then the one in memory when the program is running;Figure 7: Dump of a PE header when an Oreans protected program is running. As you can see it is not valid and is missing things like the oep and proper identification of the third section etc.As you can see there are four changes (as seen in the figure colored white) I’ll explain all of them.1. A mysterious dword added in the beginning of the PE header at 400024. It is simply antidumpchecked for existence and writing it to your new PE header is easy.2.The EP is missing at 400128. (AddressOfEntryPoint = 0) Also checked as an antidumphowever unlike the first you cannot set it to its required value (0) when dumped. You must find another way to make this zero when checked.3.Access rights to the code section are changed (from INITIALIZED_DATA, EXECUTE, READ,WRITE to CODE, EXECUTE, READ). As far as I know it is not used as an antidump.4.Random dwords are inserted into the first 5 parameters of the third section, this renders thePE header fully invalid. These dwords are checked as an antidump and either must beavailable or the antidump checking must be removed.Final Notes.I dedicate this tutorial to the challenge of cracking. May the future hold some more challenges for us to overcome. To not depend on tutorials just the urge to be challenged by developers claiming uncrackable protections. That is what drives us.I’d like to thank all crackers around the world a nd the webscene and 0day teams. Some in particular but won’t be too happy if mentioned.Regards,q.。

(Z-Stack Developer’s Guide)外文翻译

Z-Stack Developer’s Guide1. Introduction1.1 PurposeThis document explains some of the components of the ZigBee stack and their functioning. It explains the configurable parameters in the ZigBee stack and how they may be changed by the applicationdeveloper to suite theapplication requirements.1.2 ScopeThis document describes concepts and settings for the z-Stack Release v1.4.1. This is a ZigBee-2006 compliantstack.1.3 AcronymsAF Application FrameworkAIB APS Information BaseAPI Application Programming InterfaceAPS Application Support Sub-LayerAPSDE APS Date EntityAPSME APS Management EntityASDU APS Service Datagram UnitMSG MessageNHLE Next Higher Layer EntityNWK NetworkPAN Personal Area NetworkZDO ZigBee Device Object1.4 Reference DocumentsZigBee Specification, R13, ZigBee Alliance document number 053474r13ZB.ZStack API (F8W-2006-0021)2. ZigBeeA ZigBee network is a multi-hop network with battery-powered devices. This means that two devices that wish toexchange data in a ZigBee network may have to depend on other intermediate devices to be able to successfully doso. Because of this cooperative nature of the network, proper functioning requires that each device (i) performspecific networking functions and (ii) configure certain parameters to specific values. The set of networkingfunctions that a device performs determines the role of the device in the network and is called a device type. The setof parameters that need to be configured to specific values, along with those values, is called a stack profile.2.1 Device TypesThere are three logical device types in a ZigBee network – (i) Coordinator (ii) Router and (iii)End-device. AZigBee network consists of a Coordinator node and multiple Router and End-device nodes. Note that the device type does not in any way restrict the type of application that may run on the particular device.An example network is shown in the diagram above, with the ZigBee coordinator ( in black ), the routers ( in red ) and the end devices ( white ).2.1.1 CoordinatorThis is the device that “starts” a ZigBee network. It is the first device on the networ k. The coordinator node choosesa channel and a network identifier ( also called PAN ID ) and then starts the network.The coordinator node can also be used, optionally, to assist in setting up security and application-level bindings inthe network.Note that the role of the Coordinator is mainly related to starting up and configuring the network. Once that isaccomplished, the Coordinator behaves like a Router node ( or may even go away ). The continued operation of thenetwork does not depend on the presence of the Coordinator due to the distributed nature of the ZigBee network.2.1.2 RouterA Router performs functions for (i) allowing other devices to join the network (ii) multi-hop routing (iii) assisting incommunication for its child battery-powered end devices.In general, Routers are expected to be active all the time and thus have to be mains-powered. A special mode of network operation, called “Cluster Tree”, allows Routers to operate on a periodic duty cycle and thus enables them to be battery-powered.2.1.3 End-deviceAn end-device has no specific responsibility for maintaining the network infrastructure, so it can sleep and wake upas it chooses. Thus it can be a battery-powered node.Generally, the memory requirements (especially RAM requirements) are lower for an end-device. Notes:In z-stack v1.4.1, the device type is usually determined at compile-time via compile options (ZDO_ COORDINATORand RTR_NWK). All sample applications are provided with separate project files to build each device type.It is possible to create an image with both Coordinator and Router functionality and choose the device type atruntime. See the SOFT_START compile option for more details.2.2 Stack ProfileThe set of stack parameters that need to be configured to specific values, along with those values, is called a stackprofile. The parameters that comprise of the stack profile are defined by the ZigBee Alliance.All devices in a network must conform to the same stack profile (i.e., all devices must have the stackprofileparameters configured to the same values).The ZigBee Alliance has defined a stack profile for the ZigBee-2006 specification with the goal of promotinginteroperability. All devices that conform to this stack profile will able to work in a network with devices from othervendors that also conform to it.If application developers choose to change the settings for any of these parameters, they can do so with the caveatthat those devices will no longer be able to interoperate with devices from other vendors that choose to follow the ZigBee specified stack profile. Thus, developers of “closed networks” may choo se to change the settings of the stack profile variables. These stack profiles are called “network-specific” stack profile.The stack profile identifier that a device conforms to is present in the beacon transmitted by that device. Thisenables a device to determine the stack profile of a network before joining to it. The“network-specific” stack profile has an ID of 0 while the ZigBee-2006 stack profile has ID of 1. The stack profile is configured by theSTACK_PROFILE_ID parameter in nwk_globals.h file.3. Addressing3.1 Address typesZigBee devices have two types of addresses. A 64-bit IEEE address (also called MAC address or Extended address)and a 16-bit network address (also called logical address or short address).The 64-bit address is a globally unique address and is assigned to the device for its lifetime. It is usually set by themanufacturer or during installation. These addresses are maintained and allocated by the IEEE. More information onhow to acquire a block of these addresses is available at/regauth/oui/index.shtmlThe 16-bit address is assigned to a device when it joins a network and is intended for use while it is on the network.It is only unique within that network. It is used for identifying devices and sending data within the network.3.2 Network address assignmentZigBee uses a distributed addressing scheme for assigning the network addresses. This scheme ensures that allassigned network addresses are unique throughout the whole network. This is necessary so that there is no ambiguity about which device a particular packet should be routed to. Also, the distributed nature of the addressing algorithmensures that a device only has to communicate with its parent device to receive a unique network-wide address.There is no need for network-wide communication for address assignment and this helps in scalability of thenetwork.The addressing scheme requires that some parameters are known ahead of time and are configured in each routerthat joins the network. These are the MAX_DEPTH, MAX_ROUTERS andMAX_CHILDREN parameters. Theseare part of the stack profile and the ZigBee-2006 stack profile has defined values for these parameters(MAX_DEPTH = 5, MAX_CHILDREN = 20,MAX_ROUTERS = 6).The MAX_DEPTH determines the maximum depth of the network. The coordinator is at depth 0 and its child nodesare at depth 1 and their child nodes are at depth 2 and so on. Thus the MAX_DEPTH parameter limits how “long”the network can be physically.The MAX_CHILDREN parameter determines the maximum number of child nodes that a router (or coordinator)node can possess.The MAX_ROUTERS parameter determines the maximum number of router-capable child nodes that a router (orcoordinator) node can possess. This parameter is a subset of the MAX_CHILDRENparameter and the remaining(MAX_CHILDREN – MAX_ROUTERS) address space are for end devices.If developer wishes to change these values, they need to follow following steps:First it must be ensured that the new values for these parameters are legal. Since the total address space is limited toabout 216, there are limits on how large these parameters can be set to. The Cskip.xls file that is distributed in therelease (in the Projects\zstack\Tools folder) can be used to verify this. After entering the values for the parametersinto the spreadsheet, an error message will be given if the values are not legal.After choosing legal values, the developer needs to ensure not to use the standard stack profile and instead set it tonetwork-specific (i.e. change the STACK_PROFILE_ID in “nwk_globals.h” to NETWORK_SPECIFIC). Then the MAX_DEPTH parameter in “nwk_globals.h” may be set to the appropriate value.In addition, the array’s CskipChldrn and CskipRtrs must be set in the nwk_globals.c f ile. These arrays are populatedwith the values for MAX_ CHILDREN and MAX_ ROUTERS value for the firstMAX_DEPTH indices followedby a zero value.3.3 Addressing in z-stackIn order to send data to a device on the ZigBee network, the application generally uses theAF_DataRequest()function. The destination device to which the packet is to be sent of type afAddrType_t (defined in “ZComDef.h”).typedef struct{union{uint16 shortAddr;} addr;afAddrMode_t addrMode;byte endPoint;} afAddrType_t;Note that in addition to the network address, the address mode parameter also needs to be specified. The destinationaddress mode can take one of the following values (AF address modes are defined in “AF.h”)typedef enum{afAddrNotPresent = AddrNotPresent,afAddr16Bit = Addr16Bit,afAddrGroup = AddrGroup,afAddrBroadcast = AddrBroadcast} afAddrMode_t;The address mode parameter is necessary because, in ZigBee, packets can be unicast, multicast or broadcast. Aunicast packet is sent to a single device, a multicast packet is destined to a group of devices and a broadcast packet isgenerally sent to all devices in the network. This is explained in more detail below.3.3.1 UnicastThis is the normal addressing mode and is used to send a packet to a single device whose networkaddress is known.The addrMode is set to Addr16Bit and the destination network address is carried in the packet3.3.2 IndirectThis is when the application is not aware of the final destination of the packet. The mode is set to AddrNotPresent and the destination address is not specified. Instead, the destination is looked up from a“binding table” that resides in the stack of the sending device. This feature is called So urce binding (see later sectionfor details on binding).When the packet is sent down to the stack, the destination address is looked up from the binding table and used. Thepacket is then treated as a regular unicast packet. If more than one destination device is found, a copy of the packetis sent to each of them.In previous versions of ZigBee (ZigBee04), there was an option to store the binding table on the coordinator. In thatcase, the sending device would send the packet to the coordinator which would then redirect the packet to theeventual destination that is found in its binding table. This optional feature is called Coordinator Binding.3.3.3 BroadcastThis address mode is used when the application wants to send a packet to all devices in the network. The addressmode is set to AddrBroadcast and the destination address can be set to one of the following broadcast addresses:NWK_BROADCAST_SHORTADDR_DEVALL (0xFFFF) – the message will be sent to all devices in the network(includes sleeping devices). For sleeping devices, the message is held at its parent until the sleeping device polls forit or the message is timed out (NWK_INDIRECT_MSG_TIMEOUT inf8wConfig.cfg).NWK_BROADCAST_SHORTADDR_DEVRXON (0xFFFD) – the message will be sent to all devices that have thereceiver on when idle (RXONWHENIDLE). That is, all devices except sleeping devices. NWK_BROADCAST_SHORTADDR_DEVZCZR (0xFFFC) – the message is sent to all routers( including thecoordinator ).3.3.4 Group AddressingThis address mode is used when the application wants to send a packet to a group of devices. The address mode isset to afAddrGroup and the addr.shortAddr is set to the group identifier.Before using this feature, groups have to be defined in the network [see the aps_AddGroup() in the ZStack APIdoc].Note that groups can also be used in conjunction with indirect addressing. The destination address found in thebinding table can be either a unicast or a group address. Also note that broadcast addressing is simply a special caseof group addressing where the groups are setup ahead of time. Sample code for a device to add itself to a group with identifier 1:aps_Group_t group;// Assign yourself to group 1group.ID = 0x0001;[0] = 0; // This could be a human readable stringaps_AddGroup( SAMPLEAPP_ENDPOINT, &group );3.4 Important Device AddressesAn application may want to know the address of its device and that of its parent. Use the following functions to get this device’s address (defined in ZStack API Doc):• NLME_GetShortAddr() –returns this device’s 16 bit network address.• NLME_GetExtAddr() –returns this device’s 64 bit extended address.Use the following functi ons to get this device’s parent’s addresses (defined in ZSta ck API Doc). Note that the term“Coord” in these functions does not refer to the Zigbee Coordinator, but inst ead to the device’s parent (MAC Coordinator):• NLME_GetCoordShortAddr() – returns this d evice’s parent’s 16 bit short address.• NLME_GetCoordExtAddr() –returns this device’s parent’s 64 bit extended address.4. BindingBinding is a mechanism to control the flow of messages from one application to another application (or multipleapplications). In the Zigbee 2006 release, the binding mechanism is implemented in all devices and is called sourcebinding.Binding allows an application to send a packet without knowing the destination address, the APS layer determinesthe destination address from its binding table, and then forwards the message on to the destination application (ormultiple applications) or group.Notice: This is a change from the Zigbee 1.0 release, which stored all of the binding entries on coordinator. Now,all the binding entries are stored on the device that is sending the data.4.1 Building a Binding TableThere are 3 ways to build a binding table:Zigbee Device Object Bind Request – a commissioning tool can tell the device to make a binding record.• Zigbee Device Object End Device Bind Request – 2 devices can tell the coordinator that they would like tosetup a binding table record. The coordinator will make the match up and create the binding table entries inthe 2 devices.• Device Application – An application on the device can build or manage a binding table.4.1.1 Zigbee Device Object Bind RequestAny device or application can send a ZDO message to another device (over the air) to build a binding record for thatother device in the network. This is called Assisted Binding and it will create a binding entry for the sending device.4.1.1.1 The Commissioning ApplicationAn application can do this by calling ZDP_BindReq() [defined in ZDProfile.h] with 2 applications (addresses andendpoints) and the cluster ID wanted in the binding record. The first parameter (target dstAddr) is the short address of the binding’s source address (where the binding record will be stored). Make sure you have the feature enabled in ZDConfig.h [ZDO_BIND_UNBIND_REQUEST].You can use ZDP_UnbindReq() with the same parameters to remove the binding record.The target device will send back a Zigbee Device Object Bind or Unbind Response message which the ZDO codewill parse and notify ZDApp.c by calling ZDApp_BindRsp() or ZDApp_UnbindRsp() with the status of theaction.For the Bind Response, the status returned from the coordinator will be ZDP_SUCCESS,ZDP_TABLE_FULL orZDP_NOT_SUPPORTED.For the Unbind Response, the status returned from the coordinator will be ZDP_SUCCESS,ZDP_NO_ENTRY orZDP_NOT_SUPPORTED.4.1.1.2 Zigbee Device Object End Device Bind RequestThis mechanism uses a button press or other similar action at the selected devices to bind within a specific timeoutperiod. The End Device Bind Request messages are collected at the coordinator within the timeout period and aresulting Binding Table entry is created based on the agreement of profile ID and cluster ID. The default end devicebinding timeout (APS_DEFAULT_MAXBINDING_TIME) is 16 seconds (defined in nwk_globals.h), but can bechanged if added to f8wConfig.cfg.The sample applications used in the “User’s Guide” are examples of an End Device Bind implementation (pressingSW2 on each device).You’ll notice that all sample applications have a function that handles key events [for example, TransmitApp_HandleKeys() in TransmitApp.c]. This function callsZDApp_SendEndDeviceBindReq() [in ZDApp.c], which gathers all the information for the application’s endpoint and calls ZDP_EndDeviceBindReq() [ZDProfile.c] to send the message to the coordinator. Or, as inSampleLight and SampleSwitch, ZDP_EndDeviceBindReq() is called directly with only the cluster IDsrelevant to the lamp On/Off functions.The coordinator will receive [ZDP_IncomingData() in ZDProfile.c] and parse[ZDO_ProcessEndDeviceBindReq() in ZDObject.c] the message and callZDApp_EndDeviceBindReqCB() [in ZDApp.c], which calls ZDO_MatchEndDeviceBind() [ZDObject.c]to process the request.When the coordinator receives 2 matching End Device Bind Requests, it will start the process of creating sourcebinding entries in the requesting devices. The coordinator follows the following process, assuming matches werefound in the ZDO End Device Bind Requests:1. Send a ZDO Unbind Request to the first device. The End Device Bind is toggle process, so the unbind is sentfirst to remove an existing bind entry.2. Wait for the ZDO Unbind Response, if the response status is ZDP_NO_ENTRY, send a ZDO Bind Request tomake the binding entry in the source device. If the response status is ZDP_SUCCESS, move on to the clusterID for the first device (the unbind removed the entry – toggle).3. Wait for the ZDO Bind Response. When received, move on to the next cluster ID for the first device.4. When the first device is done, do the same process with the second device.5. When the second device is done, send the ZDO End Device Bind Response messages to both the first andsecond device.4.1.1.3 Device Application Binding ManagerAnother way to enter binding entries on the device is for the application to manage the binding tablefor itself.Meaning that the application will enter and remove binding table entries locally by calling the following bindingtable management functions (ref. ZStack API Document – Binding Table Management section):• bindAddEntry() – Add entry to binding table• bindRemoveEntry() – Remove entry from binding table• bindRemoveClusterIdFromList() – Remove a cluster ID from an existing binding table entry• bindAddClusterIdToList() – Add a cluster ID to an existing binding table entry• bindRemoveDev() – Remove all entries with an address reference•bindRemoveSrcDev() – Remove all entries with a referenced source address •bindUpdateAddr () – Update entries to another address•bindFindExisting () – Find a binding table entry•bindIsClusterIDinList() – Check for an existing cluster ID in a table entry•bindNumBoundTo() – Number of entries with the same address (source or destination) •bindNumOfEntries() – Number of table entries•bindCapacity() – Maximum entries allowed•BindWriteNV() – Update table in NV.4.1.2 Configuring Source BindingTo enable source binding in your device include the REFLECTOR compile flag in f8wConfig.cfg. Also inf8wConfig.cfg, look at the 2 binding configuration items (NWK_MAX_BINDING_ENTRIES &MAX_BINDING_CLUSTER_IDS). NWK_MAX_BINDING_ENTRIES is the maximum number of entries in thebinding table and MAX_BINDING_CLUSTER_IDS is the maximum number of cluster IDs in each binding entry.The binding table is maintained in static RAM (not allocated), so the number of entries and the number of clusterIDs for each entry really affect the amount of RAM used. Each binding table entry is 8 bytes plus(MAX_BINDING_CLUSTER_IDS * 2 bytes). Besides the amount of static RAM used by the binding table, thebinding configuration items also affect the number of entries in the address manager.5. Routing5.1 OverviewA mesh network is described as a network in which the routing of messages is performed as a decentralized,cooperative process involving many peer devices routing on each others’ behal f.The routing is completely transparent to the application layer. The application simply sends data destined to anydevice down to the stack which is then responsible for finding a route. This way, the application is unaware of thefact that it is operating in a multihop network.Routing also enables the “self healing” nature of ZigBee networks. If a particular wir eless link is down, the routingfunction will automatically find a new route that avoids that particular broken link. This greatly enhances thereliability of the wireless network and is one of the key features of ZigBee.5.2 Routing protocolThe ZigBee implementation uses a routing protocol that is based on the AODV (Ad hoc On demand DistanceVector) routing protocol for ad hoc networks. Simplified for use in sensor networks, the ZigBee routing protocolfacilitates an environment capable of supporting mobile nodes, link failures and packet losses.When a router receives a unicast packet, from its application or from another device, the NWK layer forwards itaccording to the following procedure. If the destination is one of the neighbors of the router (including its childdevices), the packet will be transmitted directly to the destination device. Otherwise, the router will check its routingtable for an entry corresponding to the routing destination of the packet. If there is an active routing table entry forthe destination address, the packet will be relayed to the next hop address stored in the routing entry. If an activeentry can not be found, a route discovery is initiated and the packet is buffered until that process is completed.ZigBee end-devices do not perform any routing functions. An end-device wishing to send a packet to any devicesimply forwards it to its parent device which will perform the routing on its behalf. Similarly, when any devicewishes to send a packet to an end-device and initiate route discovery, the parent of the end-device responds on itsbehalf.Note that the ZigBee address assignment scheme makes it possible to derive a route to any destination based on itsaddress. In z-stack, this mechanism is used as an automatic fallback in case the regular routing procedure cannot beinitiated (usually, due to lack of routing table space).Also in z-stack, the routing implementation has optimized the routing table storage. In general, a routing table entryis needed for each destination device. But by combining all the entries forend-devices of a particular parent with theentry for that parent device, storage is optimized without loss of any functionality.ZigBee routers, including the coordinator, perform the following routing functions (i) route discovery and selection(ii) route maintenance (iii) route expiry.5.2.1 Route Discovery and SelectionRoute discovery is the procedure whereby network devices cooperate to find and establish routes through thenetwork. A route discovery can be initiated by any router device and is always performed in regard to a particulardestination device. The route discovery mechanism searches all possible routes between the source and destinationdevices and tries to select the best possible route.Route selection is performed by choosing the route with the least possible cost. Each node constantly keeps track of"link costs" to all of its neighbors. The link cost is typically a function of the strength of the received signal. By adding up the link costs for all the links along a route, a “route cost” is derived for the whole route. The routing algorithm tries to choose the route with the least “route cost”.Routes are discovered by using request/response packets. A source device requests a route for a destination addressby broadcasting a Route Request (RREQ) packet to its neighbors. When a node receives an RREQ packet it in turn. rebroadcasts the RREQ packet. But before doing that, it updates the cost field in the RREQ packet by adding thelink cost for the latest link. This way, the RREQ packet carries the sum of the link costs along all the links that ittraverses. This process repeats until the RREQ reaches the destination device. Many copies of the RREQ will reachthe destination device traveling via different possible routes. Each of these RREQ packets will contain the total routecost along the route that it traveled. The destination device selects the best RREQ packet and sends back a RouteReply (RREP) back to the source.The RREP is unicast along the reverse routes of the intermediate nodes until it reaches the original requesting node.As the RREP packet travels back to the source, the intermediate nodes update their routing tables to indicate theroute to the destination.Once a route is created, data packets can be sent. When a node loses connectivity to its next hop (it doesn’t receive a MAC ACK when sending data packets), the node invalidates its route by sending an RERR to all nodes thatpotentially received its RREP. Upon receiving a RREQ, RREP or RERR, the nodes update their routing tables.5.2.2 Route maintenanceMesh networks provide route maintenance and self healing. Intermediate nodes keep track of transmission failuresalong a link. If a link is determined as bad, the upstream node will initiate route repair for all routes that use thatlink. This is done by initiating a rediscovery of the route the next time a data packet arrives for that route. If theroute rediscovery cannot be initiated, or it fails for some reason, a route error (RERR) packet is sent back to sourceof the data packet, which is then responsible for initiating the new route discovery. Either way the route getsreestablished automatically.5.2.3 Route expiryThe routing table maintains entries for established routes. If no data packets are sent along a route for a period oftime, the route will be marked as expired. Expired routes are not deleted until space is needed. Thus routes are notdeleted until it is absolutely necessary. The automatic route expiry time can be configured in "f8wconfig.cfg". SetROUTE_EXPIRY_TIME to expiry time in seconds. Set to 0 in order to turn off route expiry feature.5.3 Table storageThe routing functions require the routers to maintain some tables.5.3.1 Routing tableEach ZigBee router, including the ZigBee coordinator, contains a routing table in which the device storesinformation required to participate in the routing of packets. Each routing table entry contains the destinationaddress, the next hop node, and the link status. All packets sent to the destination address are routed through the nexthop node. Also entries in the routing table can expire in order to reclaim table space from entries that are no longerin use.Routing table capacity indicates that a device routing table has a free routing table entry or it already has a routingtable entry corresponding to the destination address. The routing table size is configured in "f8wconfig.cfg". SetMAX_RTG_ENTRIES to the number of entries in the (set to at least 4). See the section on Route Maintenance forroute expiration details.5.3.2 Route discovery tableRouter devices involved in route discovery, maintain a route discovery table. This table is used to store temporaryinformation while a route discovery is in progress. These entries only last for the duration of the route discoveryoperation. Once an entry expires it can be used for another route discovery operation. Thus this value determines themaximum number of route discoveries that can be simultaneously performed in the network. This value isconfigured by setting theMAX_RREQ_ENTRIES in "f8wconfig.cfg".5.4 Routing Settings Quick Reference6. Portable DevicesEnd devices, in Zigbee 2006, are automatically portable. Meaning that when an end device detects that its parent isn’t responding (out of range or incapacitated) it will try to rejoin the network (j oining a new parent). There areno setup or compile flags to setup this option.The end device detects that a parent isn’t responding either through polling (MAC data requests) failures and/orthrough data message failures. The sensitivity to the failures (amount of consecutive errors) is controlled by MAX_POLL_FAILURE_RETRIES, which is changeable in f8wConfig.cfg (the higher the number – the lesssensitive and the longer it will take to rejoin).When the network layer detects that its parent isn’t responding, it will callZDO_SyncIndicationCB(), which will initiate a “rejoin”. The rejoin process will firstorphan-scan for an existing parent, then scan for a potentialparent and rejoin (network rejoin command) the network with the potential parent.In a secure network, it is assumed that the device already has a key and a new key isn’t issued to the device.。

OGNL及其表达式

OGNL及其表达式
目标
初步理解使用OGNL的优势, 简单的OGNL表达式
初步掌握索引访问
掌握对集合进行操作 OGNL的值栈特性;
lambda表达式
2
一.ቤተ መጻሕፍቲ ባይዱGNL简介
1.OGNL概念 1)对象图导航语言,获取和设置属性的Java对象。 示例:在JSP页面中使用表达式语言获取user对象的 username <%@ page language="java" import="java.util.*,er" %> <% User user = (User)request.getAttribute("user"); out.print(username); %>
1 7
5.访问JavaBean的属性表达式
例如:有两个JavaBean类,并有一个employee对象作为OGNL上下 文的根对象? Public class Address{
Private String country; Private String city; Private String street; ……
表达式指要取谁的姓名呢?即获取在那个范围/环境的姓名 对于不同的环境/上下文,相同的表达式会有不同的结果!
4
4)OGNL表达式语言结构 Struts 2中的OGNL Context实现者为ActionContext
ValueStack(值栈,它是根对象) parameters OGNL Context request session application attr
1 0
二.简单的OGNL表达式
1.作用
表达式的计算在当前对象的上下文中,一个链简 单地使用链中先前链接的结果用作下一步计算的当 前对象 示例:导航链表达式 name.toCharArray()[0].numericValue.toString() ? 2.导航链的组成 计算: 1)属性名A. 获取根对象的name; B. 在String结果上调用toCharArray()方法 2)方法调用 C. 从char数组结果中提取第一个字符? 3)数组索引 D. 从提取的字符对象上得到numericValue属性

Appendix


Appendix
12
Client-Server Model

Client
o “speaks first”

Server
o tries to respond to request

Hosts are clients and/or servers
Example: Web browsing
o You are the client (request web page) o Web server is the server
mesh of routers

Purpose is to move data from host to host
Appendix
6
Packet Switched Network

Telephone network is/was circuit switched
o For each call, a dedicated circuit established o Dedicated bandwidth

host
At source, data goes “down” the protocol stack Each router processes packet “up” to network layer
o That’s where routing info lives
Router then passes packet down the protocol stack Destination processes up to application layer
Appendix
7
Network Protocols

Silicon Labs Bluetooth Mesh 灯具示例说明书

QSG148: Getting Started with the Silicon Labs Bluetooth® Mesh Lighting Demonstration in SDK 1.xThis document provides step-by-step instructions to demonstratea basic Bluetooth mesh network. In this demo, three Wireless Starter Kit (WSTK)-based devices are provisioned as two Lights and one Switch. The mobile application allows the control of ei-ther the group of Lights or an individual Light. By pressing but-tons on the Switch device, you can control the ON/OFF states and brightness for all lights in the same group. The demo is open-sourced and provides a good demonstration of a basic Bluetooth mesh network.The Bluetooth Mesh mobile app is intended to demonstrate the Silicon Labs Bluetooth Mesh technology together with the Bluetooth Mesh SDK sample apps. The mobile app is a reference app for the Bluetooth Mesh mobile ADK but it should not be taken as a starting point for customers to create their own mobile apps. For guidance on creating mobile apps with the Bluetooth Mesh mobile ADK, refer to AN1200: Bluetooth® Mesh for iOS and Android ADK.KEY POINTS•Prerequisite for the demo•Hardware set-up of WTSKs •Bluetooth mesh SDK installation in Simplicity Studio•Demo firmware installation •Instructions for provisioning, configuring, and controlling network nodes using the Android smartphone applicationPrerequisites 1. PrerequisitesThe Silicon Labs Bluetooth mesh lighting demonstration is designed to illustrate Bluetooth mesh operation without any need to config-ure or compile software. To get started with the Bluetooth mesh demo, obtain the following.1.1 Order Development KitsThe Blue Gecko Bluetooth SoC Wireless Starter Kit is the easiest and fastest way to start the evaluation and development of your own Bluetooth mesh applications. To get started with the Bluetooth mesh demo, you need to have three (3) EFR32™ WSTK main boards and radio boards. These can be obtained by ordering any of the Wireless Starter Kit options below.Option 1:QTY(3) of PN: SLWSTK6020B kits: /products/development-tools/wireless/bluetooth/blue-gecko-bluetooth-low-energy-soc-starter-kitOption 2:QTY(1) of PN: SLWSTK6000B kit: /products/development-tools/wireless/mesh-networking/mighty-gecko-starter-kitOption 3: QTY(1) of PN: SLWSTK6006A kit: /products/development-tools/wireless/efr32xg21-wireless-starter-kitThis demo requires either EFR32MG21, EFR32BG13, EFR32MG13, EFR32BG12, or EFR32MG12 radio boards. If you already have the WSTK Main Boards, you can purchase the required radio boards here.Note: This document references the boards provided in PN: SLWSTK6020B. The radio board provided in SLWSTK6000B and SLWSTK6006A as well as the radio board mentioned above can be substituted for the EFR32BG13 board referenced in this document.1.2 Download Simplicity StudioGo to: /simplicity-studio to download the latest Simplicity Studio version compatible with your computer’s operat-ing system.1.3 Download Bluetooth Mesh by Silicon Labs Mobile App from iTunes or Google PlayiTunes:https:///us/app/bluetooth-mesh-by-silicon-labs/id1411352948?mt=8Google Play:https:///store/apps/details?id=com.siliconlabs.bluetoothmesh&hl=enNote: The minimum requirement for the smartphone is Android 6 (API23).1.4 Obtaining SupportYou can access the Silicon Labs support portal at https:///support through Simplicity Studio Resources. Click the “Email-Support” link and log in with your self-registered credentials. Use the support portal to contact Customer Support for any ques-tions you might have about the demonstration.2. About the Bluetooth Mesh SDKThe Silicon Labs Bluetooth mesh stack is an advanced Bluetooth mesh protocol stack implementing the Bluetooth mesh standard. It can run alongside the Bluetooth Low Energy (LE) stack, using a common link layer, which allows using LE features in parallel. The Silicon Labs Bluetooth mesh stack is meant for Silicon labs Wireless Gecko SoCs and modules.The Silicon Labs Bluetooth mesh stack provides multiple APIs for the developer to access the Bluetooth mesh functionality. Two modes are supported.1.Standalone mode (also referenced as SoC mode), where both the Bluetooth mesh stack and the application run in a WirelessGecko SoC or module. The application can be developed with the C programming language.work Co-Processor (NCP) mode, where the Bluetooth stack runs in a Wireless Gecko and the application runs on a separatehost MCU. For this use case, the Bluetooth stack can be configured into NCP mode where the API is exposed over a serial inter-face such as UART.2.1 Bluetooth Mesh Stack FeaturesThe features of the Silicon Labs Bluetooth stack are listed in the following table. For details on the features of the Bluetooth Low Ener-gy stack, refer to QSG139: Getting Started with Bluetooth® Software Development.Table 2.1. Bluetooth Mesh Stack FeaturesTable 2.2. Supported Models2.2 Bluetooth Mesh Stack Limitations(1) The node belongs to a single network but the network may have multiple network keys to encrypt the traffic.3. Getting Started3.1 Preparing the WSTKThe layout of the Wireless Starter Kit (WSTK) Main Board with attached EFR32BG13 radio board is shown in the following figure:Figure 3.1. WSTK Main Board with Radio Board Attached1.Connect a Blue Gecko Radio Board to the WSTK Main Board.Use radio board SLWRB4104A EFR32BG13 2.4 GHz (+10 dBm) for this demo experience.2.Connect the WSTK to a PC using the "J-Link USB" connector and the cable provided with the starter kit.3.If not already set, turn the Power switch to "AEM" position.4.Repeat the above steps for the other two kits so all three kits are connected to your computer.Verifying the Setup:1.Check that the blue "USB Connection Indicator" LED (next to “J-Link USB”) turns on or starts blinking.2.Check that the Main Board LCD display turns on and displays a Silicon Labs logo.For more detailed information regarding the Starter Kit, refer to UG279: EFR32BG13 Blue Gecko Bluetooth Starter Kit User's Guide.3.2 Open Simplicity Studio and Install Bluetooth Mesh SDKBluetooth mesh SDK is installed using the Simplicity Studio package manager.1.Open Simplicity Studio and log in using your Silicon Labs account.2.Click the Download Update icon (red/green down arrow under the menu bars), and click Package Manager.3.Go to the SDKs tab to install Bluetooth mesh SDK.4.In the Launcher screen, check if the preferred SDK is “Bluetooth mesh SDK + Platform”. If not, click the link provided to change thepreferred SDK to “Bluetooth mesh SDK + Platform”.You can find more detailed instructions for Simplicity Studio in QSG139: Bluetooth Development with Simplicity Studio.3.3 Install the Demonstration FirmwareWhen the devices are connected to your PC with a USB cable, you can see three devices listed in the Device window in Simplicity Studio. Select the J-link for a device to display demonstrations, examples, and documentation associated with the Bluetooth Mesh SDK.For this demo, you need to flash two devices with BT Mesh – Light Example and one device with BT Mesh – Switch Example.To install the firmware, click the demo. In the Mode drop-down in the next dialog, select Run. Click [Start].3.4 Use the Demo with an Android SmartphoneMake sure that all three devices have the status of “unprovisioned” on the device LCD screen before starting with the application. Open the Bluetooth Mesh App by Silicon Labs on your Android phone.Follow the procedures below to set up and use the demonstration.1.Go to provisioning view and search for unprovisioned devices.2.Select the Bluetooth mesh device you want to provision and configure.3.Enter the descriptive name for the device and the network you want to add it to.Note: The Android application has a pre-generated network and group, but you can add more groups to the application if you like. The network and node database can be erased by long-pressing the network in the main view and by pressing the trash icon.To configure the newly provisioned Bluetooth mesh:1.Right after provisioning the Android application connects the proxy service on the node.2.During configuration select the Bluetooth mesh features (proxy, relay, low power, and friend) that you want to enable.a.Notice that if you disable proxy, the node can no longer be directly accessed over GATT.3.Select the functionality (mesh model) that you want to enable.4.Select the group you want to add the device to.Note: The information view shows the Bluetooth mesh node features, such as Unicast address, UUID, and security keys as well as the supported mesh models. It can be used for debug purposes.To control a Bluetooth mesh node with the Android application:1.Select the network and group you want to control .2.The application will show the available nodes in that group.3.You can control the light:a.Pressing the light bulb icon will send an On/Off message.b.Moving the upper slider will send Light Lightness (dimming) messages.c.Moving the medium and lower sliders will send CTL (temperature and delta UV) messages.d.Pressing [STORE] stores the corresponding scene.4.By going to devices view and either swiping or long-pressing a node you can then either delete or reconfigure the node.Once the Android application has been used to provision a light bulb and a light switch to a network and group, the light switch (WSTK) can also be used to control the light bulb (WSTK) with the PB0 and PB1 buttons.PB0 button:•Short press: Decrease Light Lightness by 10%•Medium press: Decrease CTL (temperature) value•Long press: Send Off message•Very long press (5 seconds or more): Recall scene 1PB1 button:•Short press: Increase Light Lightness by 10%•Medium press: Increase CTL (temperature) value•Long press: Send On message•Very long press (5 seconds or more): Recall scene 23.5 Use the Demo with an iOS SmartphoneMake sure that all three devices have the status of “unprovisioned” on the device LCD screen before starting with the Mobile App.Open the Bluetooth Mesh App by Silicon Labs on your iOS phone.Follow the procedures below to set up and use the demonstration.1.Create a Bluetooth mesh network.2.Select the network and create a group.3.Go to the provisioning view and search for unprovisioned devices.4.Select the Bluetooth mesh device you want to provision and configure.The network and node database can be erased by left-swiping the network in the main view and then pressing the trash icon.To provision a Bluetooth mesh device and configure the node:1.During provisioning select the network you want to add the device to.2.During configuration select the Bluetooth mesh features (proxy, relay, low power and friend) that you want to enable.a.Notice that if you disable proxy, the node can no longer be directly accessed over GATT.3.Select the group you want to add the device to.4.Finally select the functionality (mesh model) that you want to enable.Note: The information view shows the Bluetooth mesh node features, such as Unicast address, UUID, and security keys as well as the supported mesh models. It can be used for debug purposes.To control a Bluetooth mesh node with the iOS application:1.Select the network and group you want to control.2.The application will show the available nodes in that group.3.You can control the light:a.Pressing the light bulb icon will send an On/Off message.b.Moving the upper slider will send Light Lightness (dimming) messages.c.Moving the medium and lower sliders will send CTL (temperature and delta UV) messages.d.Pressing [STORE] stores the corresponding scene.4.By going to the Devices view and tapping a node name you can reconfigure the node. To remove the node from the network, left-swipe it and press the trash icon.Once the iOS application has been used to provision a light bulb and a light switch to a network and group, the light switch (WSTK) can also be used to control the light bulb (WSTK) with the PB0 and PB1 buttons.PB0 button:•Short press: Decrease Light Lightness by 10%•Medium press: Decrease CTL (temperature) value•Long press: Send Off message•Very long press (5 seconds or more): Recall scene 1PB1 button:•Short press: Increase Light Lightness by 10%•Medium press: Increase CTL (temperature) value•Long press: Send On message•Very long press (5 seconds or more): Recall scene 24. Next StepsTo understand how the demo works, see AN1098: Understanding the Silicon Labs Bluetooth Mesh Lighting Demonstration .Explore the other documentation provided by Silicon Labs to get started with customizing your own Bluetooth mesh applications. SDK-specific documentation is provided under SDK Documentationon the Getting Started tab of the Launcher perspective.Next StepsIoT Portfolio/IoT SW/HW /simplicity Quality /quality Support & Community /communitySilicon Laboratories Inc.400 West Cesar Chavez Austin, TX 78701USADisclaimerSilicon Labs intends to provide customers with the latest, accurate, and in-depth documentation of all peripherals and modules available for system and software implementers using or intending to use the Silicon Labs products. Characterization data, available modules and peripherals, memory sizes and memory addresses refer to each specific device, and “Typical” parameters provided can and do vary in different applications. Application examples described herein are for illustrative purposes only. Silicon Labs reserves the right to make changes without further notice to the product information, specifications, and descriptions herein, and does not give warranties as to the accuracy or completeness of the included information. Without prior notification, Silicon Labs may update product firmware during the manufacturing process for security or reliability reasons. Such changes will not alter the specifications or the performance of the product. Silicon Labs shall have no liability for the consequences of use of the information supplied in this document. This document does not imply or expressly grant any license to design or fabricate any integrated circuits. The products are not designed or authorized to be used within any FDA Class III devices, applications for which FDA premarket approval is required, or Life Support Systems without the specific written consent of Silicon Labs. A “Life Support System” is any product or system intended to support or sustain life and/or health, which, if it fails, can be reasonably expected to result in significant personal injury or death. Silicon Labs products are not designed or authorized for military applications. Silicon Labs products shall under no circumstances be used in weapons of mass destruction including (but not limited to) nuclear, biological or chemical weapons, ormissiles capable of delivering such weapons. Silicon Labs disclaims all express and implied warranties and shall not be responsible or liable for any injuries or damages related to use of a Silicon Labs product in such unauthorized applications.Trademark InformationSilicon Laboratories Inc.®, Silicon Laboratories®, Silicon Labs®, SiLabs® and the Silicon Labs logo®, Bluegiga®, Bluegiga Logo®, ClockBuilder®, CMEMS®, DSPLL®, EFM®, EFM32®, EFR, Ember®, Energy Micro, Energy Micro logo and combinations thereof, “the world’s most energy friendly microcontrollers”, Ember®, EZLink®, EZRadio®, EZRadioPRO®, Gecko®, Gecko OS, Gecko OS Studio, ISOmodem®, Precision32®, ProSLIC®, Simplicity Studio®, SiPHY®, Telegesis, the Telegesis Logo®, USBXpress®, Zentri, the Zentri logo and Zentri DMS, Z-Wave®, and others are trademarks or registered trademarks of Silicon Labs. ARM, CORTEX, Cortex-M3 and THUMB are trademarks or registered trademarks of ARM Holdings. Keil is a registered trademark of ARM Limited. Wi-Fi is a registered trademark of the Wi-Fi Alliance. All other products or brand names mentioned herein are trademarks of their respective holders.。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

100
50 25 12 6 3 1 0 0 0 1 0
• print the remainders in backward order.
Stack is an ideal structure to implement this process.
2 2
0
1 1
e.g Convert decimal number to octal number
Algorithm DecimaltoBinary
Parsing
Parsing is any logic that breaks data into
independent pieces for further processing.
For example: to translate a source program
Transform expression with stack
A*B AB*
1.Read and copy the first operand A to the result, we get “A”. 2.Read the operator “*” and push it into a stack for later use. 3.Read and copy the second operand B to the result, we can get “AB”. 4.Finish scanning the source expression, pop up the operator and concatenate it to the result, we get “AB*”
to machine language
括弧匹配检验
假设表达式中允许包含两种括号:圆括号和 方括号,其嵌套的顺序随意,如: ([ ]())或[([ ][ ])]等为正确 的匹配 [( ])或([ ]( )或 ( ( ) ) )均为错误的匹 配。
要求检验一个给定表达式中的括 弧是否正确匹配?
检验括号是否匹配的方法可用“期待的急迫程度”这个概
Fill stack
4
loop(not end of data AND not fullStack(stack)) stack(statements 4-5), then pop 1 pushStack(stack, number) 2 prompt (Enter nextthem out successively number: <EOF> to stop) 3 read(number) (statements 6-7) . Because stack 5 end loop is a LIFO data structure, the Now print numbers in reverse order of the item has been 6 Loop (not emptyStack(stack)) reversed. 1 popStack(stack dataOut) 2 print(dataOut) 7 end loop end reverseNumber
Precedence rule
the priority of an operator pushed into the
stack is higher than the operator at the top of the stack -------push it into the stack. the operator at the top of the stack has a higher priority than or equal to the current operator -------it is popped and placed in the output expression.
Examples of manual transformation
A+B*C (A+(B*C)) (A+B)*C+D+E*F-G
(((((A+B)*C)+D)+(E*F))-G)
(A+(BC *))
(A(BC *) +)
(((((AB+)C*)D+)(EF*)+)G-)
AB+C*D+EF*+GABC*+
expression.
Stack can hold the left parts of these segments while
scanning an expression or a statement for the later comparing.
Algorithm parseParens
Reverse a List
algorithm reverseNumber This program reverses a list of integers read from the keyboard by pushing them into a stack and retrieving them one by one. 1 createStack( stack) 2 prompt (Enter a number) The idea lies in reversing data iserstand. First,
显然,必须将先后出现的左括弧依次保存,为了反映这
个优先程度,保存左括弧的结构用栈最合适。这样对出 现的右括弧来说,只要"栈顶元素"相匹配即可。如果在 栈顶的那个左括弧正好和它匹配,就可将它从栈顶删除 。
Unmatched Parentheses Example
Parentheses must be matched in an algebraic
Stack Applications
Typical stack applications can be classified into four broad categories: Reversing data Reverse a List Convert decimal to binary Parsing data Parse parentheses Postponing data usage Infix to postfix transformation Evaluating postfix expressions Backtracking steps goal seeking Eight Queens Problem
Parse parentheses
This algorithm reads a source program and parses it to make sure all opening-closing parentheses are paired. 1 loop (more data) 1 read (character) 2 if (character is an opening parenthesis) 1 pushStack (stack, character) 3 else 1 if (character is closing parenthesis) 1 if (emptyStack (stack)) 1 print (Closing parenthesis not matched alert) 2 else 1 popStack(stack,token) and to match 3 end if 2 end if 4 end if 2 end loop 3 if (not emptyStack(stack)) 1 print (Opening parenthesis not matched alert) 4 end if end parseParens
Manual transformation
Fully parenthesize the expression using any
explicit parentheses Changing all infix notations in each parenthesis to postfix notation, starting from the innermost expressions Remove all parentheses.
postfix notation: 也叫逆波兰式(Reverse Polish notation, RPN,或逆波兰记法),
Infix to postfix transformation
Infix: a+b Prefix: +ab Postfix: ab+
High-level language use the infix convert it to postfix
push each item one by one into
Convert decimal to binary
•divide decimal number by 2 continuously
• record the remainders until the quotient becomes 0
2
2 2 2 2
念来描述。 例如考虑下列括号序列: [ ( [ ][ ] ) ] 12 345 6 78 即后出现的“左括弧”,它等待与其匹配的“右括弧”出现 的“急迫”心情要比先出现的左中括弧高。对“左括弧”来 说,后出现的比先出现的“优先”等待检验。 对“右括弧”来说,每个出现的右括弧要去找在它之前“ 最后”出现的那个左括弧去匹配。
Postponing data usage
Postponement means deferring data usage until
some later point(or something happens). An arithmetic expression can be expressed in three different ways: Infix, prefix, and postfix. In source program, it is often expressed with infix format, but before an expression is calculated in computer, it is usually transformed into postfix expressions.
相关文档
最新文档