Wednesday, March 29, 2017

Interview Question on C and CPP

-------------------HCL------------------   
1. Storage class  (register 16bit, 32bit, 64bit)-- depend on register we can allocated, if register is not availabe then it act as auto.

2. Memory layout

3. program of pre increment and postincrement

4. program--> Pllindorme ( number and stirng)

5. Types of environment variable in linux.

6. Relative path and Absolute path.

7. Copy constructor
class A {
A(A & B){} /how
A(A nn){} // what is difference
};
8. STL is static polymorphism ( correct)
9. For string if we pass it will as it is or we have to do some thing.






----------------------------------------------------

1.  how to prevent the class from inheretance.
Ans:=-- By creating the singltion class, by making the constructor and distructor as private.

2. virtual distructor/constructer.
Ans-- virtual distructor is possible, but virtual constructor is not possible ( compile time error)

3. function pointer
Ans-- int (*pt2Function)(float, char, char) = NULL;                        // C
int (TMyClass::*pt2Member)(float, char, char) = NULL;                // C++
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;     // C++

4. int constant pointer and constant integer constant pointer .
Ans-->
int constant pointer--- >>> int *const p;
constant int constant pointer--> const int *const p;

4.difference between the class and strucure ( is structure follow the oops concept).
Ans--
1.by default data member of class is private, and for strructure is public.
2. When we inherit the class to another class it is by default is private, but for structure-- when we inherit class in structure then by default it is pubilc.

5. stack coding - got it

6.class a; cout << sizeof (a).
Ans--- 1 because it will give minimum nonzero to it. so minimum nonzero is 1.

7. static virtual function.
Ans-- we can't declare both static and virtual function at a time.

8. Multiple inheritance y in c++ not in others.

9. how to initilize arrary of object 10. With same value.
Ans-- if we are making object of class then we initilize by using constructor.
but for int a[10] ---- for that still searching.
ANs----- std::vector a(10, Fred(5,7)); the 10 Fred objects in std::vector a will be initialized with Fred(5,7)


10. type of inherientance in C++.
Ans--> single, multiple, multi level, hybrid, hierarchical

11. class a;
{
}
main ()
{
a aa =new a();
free (a);
}QQQ-- what it will give error in compile time or run time, for that we have to include the stdlib.h
-- then it will work fine.
Ans----- free is not declared in this scope.

12. copy constructur working and usages.
Ans-- it is present by default.
construcotr (&copy)---- class a1 = a2;

13. why we use virtual distructor.

Ans-- when we are making object of base class of child class type, and if we delete base object, then it will not delete the child class distructor, so we are making the virtual distructor, then it will call the child distructor.

14. what is STL. ( Standard Templet library

Sequences
•
C++ Vectors
•
C++ Lists
•
C++ Double-Ended Queues
•
Container Adapters
•
C++ Stacks
•
C++ Queues
•
C++ Priority Queues
•
Associative Containers
•
C++ Bitsets
•
C++ Maps
•
C++ Multimaps
•
C++ Sets
•
C++ Multisets
)

15. what default will created when we create only class??
Ans--> copy constructor,default constructor, distructor, assignment operator, address operator

16. how to delete array object at one shot.  like questin 9. ( int* a= new int [10];  for deletion we will use (delete []a;) )

17. deep copy and shallow copy and when we use deep and when we use shallow.
Ans: deep copy : it create a local copy or and do operation, it will not refelect to the original one, performance is slow.
shallow copy: it refer to the data, its performance is better than the deep copy, if the data size is large, instead of copy the large data, we can pass the reference of data.

18. which operator we can not overload.
Ans:-- the operator which we can't overload
.(member access  or dot operatior), ?: ( ternary or conditional operator), :: ( scope resoloution operator), .*(pointer to member operatior), sizeof,typeid

19. Dagling pointer: is a pointer pointing to something that has been deallocated using delete.

20. Learn Design Pattern.
1. Singlton .

21. Late binding ( It is used by using the keyword virtual)- Run time it will decide which function will call .
--------------------------- asked in shell script---

Questions Asked in the interviews::

1. Automation of the jobs--- (crontab)
2. how to debug the shell script (set -x)
3. If we remove the Header of the script then also script will run ( script will also run)
4. How to check the how many socket descriptor are opened (netstat) (lsof)
=================================================================================================================================
1. What is Embedded System.
Ans-- it is computer system which will do dedicated function within a larger machenical and electrical system
2. Types of scheduling.
Ans-- ( Long Term Scheduler, Short Term scheduler, Medium Term Schedler)
3. What is ARM
Ans-- ARM is  family of instruction set archeticture  for computer process based on RISC(reduce instruction set computing)
4. What is Toolchain.
Ans--
The GNU toolchain is a blanket term for a collection of programming tools produced by the GNU Project. These tools form a toolchain (suite of tools used in a serial manner) used for developing applications and operating systems.

5. declaration of array dynamic ( c and c++) and delete it.
Ans--
IN C lang
int i[size];

int *ii = (int *) malloc (size *sizeof(int) );

IN C++ lang
int i[size];
int *ii =new int[size];


6. What is sizeof.

7. how to compile toolchain.

8. IPC mechanism and types of IPC.
Ans-- Socket programming, shared memory


9. Class follow Abstraction of OOPS concept.

10. How the process are Synchronizating.
Ans-- By using the semaphore variable and Mutex varible.

11. Use of constructor??
Ans---
When you instantiate an object it's constructor will be invoked whereas calling a method is always optional. You therefore might forget to call your initialization method and fail to initialize everything correctly.

12. What is split tool, what it will give. ( it is static analysis tool)

13. Can we increment or decrement a void pointer?
Ans-- No


14. Friend functions have the following properties:

    1) Friend of the class can be member of some other class.
    2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND.
    3) Friend can access the private or protected members of the class in which they are declared to be friend, but they can use the members for a specific object.
    4) Friends are non-members hence do not get “this” pointer.
    5) Friends, can be friend of more than one class, hence they can be used for message passing between the classes.
    6) Friend can be declared anywhere (in public, protected or private section) in the class.

15. Friend class is also possible.

16. RTTI( Run time type information)
untime Type Information (RTTI) is the concept of determining the type of any variable during execution (runtime.) The RTTI mechanism contains:

    The operator dynamic_cast
    The operator typeid
    The struct type_info

17. Types of Ploymorphism:
    a) Run Time ( dynamic  binding)   
    b) compile tiem ( static binding)


18. Data encapsulation led to the important OOP concept of data hiding.
19.  data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user


20. char *s = "Hello world";

will place Hello world in the read-only parts of the memory and making s a pointer to that, making any writing operation on this memory illegal. While doing:

char s[] = "Hello world";

puts the literal string in read-only memory and copies the string to newly allocated memory on the stack. Making

s[0] = 'J'; ( legal)


21.
When the processor wakes up after power on, it goes to a particular memory location. What is that memory location called? ??
Ans-processor goes to MBR (master boot record) then it takes the address of boot loader form thr and execute this boot loader program

22.
 Differentiate between a template class and class template.

Template class: A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates. Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

23.
 What are proxy objects?

Objects that stand for other objects are called proxy objects or surrogates.
template <class t="">
class Array2D
{
public:
class Array1D
{
public:
T& operator[] (int index);
const T& operator[] (int index)const;
};

Array1D operator[] (int index);
const Array1D operator[] (int index) const;
};

The following then becomes legal:

Array2D<float>data(10,20);
cout<<data[3][6]; // fine

Here data[3] yields an Array1D object and the operator [] invocation on that object yields the float in position(3,6) of the original two dimensional array. Clients of the Array2D class need not be aware of the presence of the Array1D class. Objects of this latter class stand for one-dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients program as if they were using real, live, two-dimensional arrays. Each Array1D object stands for a one-dimensional array that is absent from a conceptual model used by the clients of Array2D. In the above example, Array1D is a proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not exist.

24.
 Differences of C and C++
Could you write a small program that will compile in “C” but not in “C++”?

In C, if you can a const variable e.g.
const int i = 2;
you can use this variable in other module as follows
extern const int i;
C compiler will not complain.

But for C++ compiler u must write
extern const int i = 2;
else error would be generated.

25.
 What is the difference between Mutex and Binary semaphore?

semaphore is used to synchronize processes. where as mutex is used to provide synchronization between threads running in the same process

26.
 What problem does the namespace feature solve?

Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library’s external declarations with a unique namespace that eliminates the potential for those collisions.
This solution assumes that two library vendors don’t use the same namespace identifier, of course.
27.
 Describe run-time type identification.

The ability to determine at run time the type of an object by using the typeid operator or the dynamic_cast operator.

28.
Amonog all the available IPCs, Shared Memory is the best and fastest one. We need to use Shared memory when more
than one proceses wish to communicate each other on a common read-only memory. It is fast because it does not
involve physical moment of data as the data is shared among them.

Mutex/Semaphore is the best when a resource(including memory) is non-shared

29.
What is the difference between dead-lock and live-lock

DEADLOCK Deadlock is a condition in which a task waits indefinitely for conditions that can never be satisfied - task claims exclusive control over shared resources - task holds resources while waiting for other resources to be released - tasks cannot be forced to relinguish resources - a circular waiting condition exists

LIVELOCK Livelock conditions can arise when two or more tasks depend on and use the some resource causing a circular dependency condition where those tasks continue running forever, thus blocking all lower priority level tasks from running (these lower priority tasks experience a condition called starvation).
    A livelock is similar to a deadlock, except that the states of the processes involved in the livelock constantly change with regard to one another, none progressing. Livelock is a special case of resource starvation; the general definition only states that a specific process is not progressing.
    A real-world example of livelock occurs when two people meet in a narrow corridor, and each tries to be polite by moving aside to let the other pass, but they end up swaying from side to side without making any progress because they both repeatedly move the same way at the same time.
    Livelock is a risk with some algorithms that detect and recover from deadlock. If more than one process takes action, the deadlock detection algorithm can be repeatedly triggered. This can be avoided by ensuring that only one process (chosen randomly or by priority) takes action.


30.
Synchronous Sockets--( Blocking )--
A read on a socket can't complete until some data has been send by the remote host. If there is no data waiting to be read, one of two things can happen:
Function can wait until somedata is written on the socket. or
ASynchronous Sockets-- ( Non Blocking) - It can return immediately with an error that indicate that there is no data to be read.

31. Livelock-- A livelock is similar to a deadlock, except that the states of the processess invlolved in the livelock constantly change with regards to one another, none progressing .
Necessary condition of Deadlock-

Mutual exclusion- At least one resource must be held in a non-sharable mode,ONly one precess can use the resource at any given instant of time.
Hold and wait- A precess is currently holding at least one resource and requesting additional resource whic are being held by other process
No preemption-The Operating system must not de-allocate resource once they have been allocated; they must be released by the holding precess voluntarily.
Circular wait- A process must be waiting for a resourse with is being held by another process, which is turn is waithing for the first prcess to release the resources

32. Difference between structure and union:
Ans--
Structure
A structure allocates memory for each field in the structure.
We can access all the members of structure at anytime
All members of structure can be initialized.
'struct' keyword is used to declare structure..

Union:
A union only allocates enough memory to hold the largest field in the union.
Only one member of union can be accessed at anytime.
Only the first member of a union can be initialized.
'union' keyword is used to declare union.

--------Dead lock handling

1. Dead lock detection
( process termitation, resource preemption)


There are three general cases where the copy constructor is called instead of the assignment operator:
1.When instantiating one object and initializing it with values from another object
2.When passing an object by value
3. When an object is returned from a function by value.


33. So, using templates, we can write programs that do computation at compile time, such programs are called template metaprograms.
Example
#include <iostream>
using namespace std;

template<int n> struct funStruct
{
    enum { val = 2*funStruct<n-1>::val };
};

template<> struct funStruct<0>
{
    enum { val = 1 };
};

int main()
{
    cout << funStruct<8>::val << endl;
    return 0;
}
Output:
256

34. What is vitural base class.
Ans-- When we use virtual base class, then we get only one single instance of common base class.

35. Parameter passing in overloading. (like arry, pointer, etc).

36. 'Is-a relationship'-- It use public inheritance. (Ex-- every operation applied on employee will be applied on Manager)

37. 'Has-a relationship' -- It use private inheritance. ( Ex. Car has Wheel) -- class car : private wheel

38.Solving the Diamond Problem with Virtual Inheritance.

Example:

class transmitter: public virtual storable
{
        public:
        void read();
        ...
}

class receiver: public virtual storable
{
        public:
        void read();
        ...
}

When we use virtual inheritance, we are guaranteed to get only a single instance of the common base class. In other words, the radio class will have only a single instance of the storable class, shared by both the transmitter and receiver classes. By having a single instance of storable, we've resolved the compiler's immediate issue, the ambiguity, and the code will compile fine.

Memory Layout in Virtual Inheritance
In order to keep track of the single instance of the storable object, the compiler will provide a virtual function table (vtable) for classes transmitter and receiver. When a radio object is constructed, it creates one storable instance, a transmitter instance and a receiver instance. The transmitter and receiver classes have a virtual pointer in their vtables that stores the offset to the storable class. When the transmitter class or the receiver class goes to access any fields of the storable, it uses the virtual pointer in its vtable to find the storable object and find the field in it. This tutorial offers a comprehensive explanation of the memory layout of virtual inheritance in GCC.
--------------------------
Question:

1. paging
3. parameter of ( send and recv)
4. file ( go to particular location)
5. why malloc will return void *
6. Dangling pointer

Deep copy:-
It's equivalent to B* b3 = b2. The pointers will point to the same location. When you do delete b2;, you're also freeing the memory pointed to by b3.

To do a deep copy, do:

 B* b3 = new B(*b2);

-------------------------------------------------
1. What is the output of printf("%d")
2. Difference between "C structure" and "C++ structure".
3. Difference between a "assignment operator" and a "copy constructor"
4. What is the difference between "overloading" and "overriding"?
5. Explain the need for "Virtual Destructor".
6. Can we have "Virtual Constructors"?
7. What are the different types of polymorphism?
8. What are Virtual Functions? How to implement virtual functions in "C"
9. What are the different types of Storage classes?
10. What is Namespace?
11. What are the types of STL containers?.
12. Difference between "vector" and "array"?
13. How to write a program such that it will delete itself after execution?
14. Can we generate a C++ source code from the binary file?
15. What are inline functions?
16. Talk something about profiling?
17. How many lines of code you have written for a single program?
18. What is "strstream" ?
19. How to write Multithreaded applications using C++?
20. Explain "passing by value", "passing by pointer" and "passing by reference"
21. Write any small program that will compile in "C" but not in "C++"
22. Have you heard of "mutable" keyword?
23. What is a "RTTI"?
24. Is there something that I can do in C and not in C++?
25. Why preincrement operator is faster than postincrement?
26. What is the difference between "calloc" and "malloc"?
27. What will happen if I allocate memory using "new" and free it using "free" or
allocate sing "calloc" and free it using "delete"?
28. What is Memory Alignment?
29. Explain working of printf.
30. Difference between "printf" and "sprintf".
31. What is "map" in STL?
32. When shall I use Multiple Inheritance?
33. What are the techniques you use for debugging?
34. How to reduce a final size of executable?
35. Give 2 examples of a code optimization.
-----------------------------------------------




Interview Question on Bluetooth

Question Asked in Qualcomm:

1. How to increase or decrease the priority of task in Bluedroid stack.

https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/4128e36%5E!/

we are using the int setpriority(int which, int who, int prio); System call

The getpriority() call returns the highest priority (lowest numerical value) enjoyed by any of the specified processes. 

The setpriority() call sets the priorities of all of the specified processes to the specified value. Only the superuser may lower priorities.

A child created by fork(2) inherits its parent's nice value.


28typedef enum {
29    TASK_HIGH_MEDIA = 0,
30    TASK_HIGH_GKI_TIMER,
31    TASK_HIGH_BTU,
32    TASK_HIGH_HCI_WORKER,
33    TASK_HIGH_USERIAL_READ,
34    TASK_UIPC_READ,
35    TASK_JAVA_ALARM,
36    TASK_HIGH_MAX
37} tHIGH_PRIORITY_TASK;

/system/core/include/system/thread_defs.h
enum {
    /*
     * ***********************************************
     * ** Keep in sync with android.os.Process.java **
     * ***********************************************
     *
     * This maps directly to the "nice" priorities we use in Android.
     * A thread priority should be chosen inverse-proportionally to
     * the amount of work the thread is expected to do. The more work
     * a thread will do, the less favorable priority it should get so that
     * it doesn't starve the system. Threads not behaving properly might
     * be "punished" by the kernel.
     * Use the levels below when appropriate. Intermediate values are
     * acceptable, preferably use the {MORE|LESS}_FAVORABLE constants below.
     */
    ANDROID_PRIORITY_LOWEST         =  19,

    /* use for background tasks */
    ANDROID_PRIORITY_BACKGROUND     =  10,

    /* most threads run at normal priority */
    ANDROID_PRIORITY_NORMAL         =   0,

    /* threads currently running a UI that the user is interacting with */
    ANDROID_PRIORITY_FOREGROUND     =  -2,

    /* the main UI thread has a slightly more favorable priority */
    ANDROID_PRIORITY_DISPLAY        =  -4,

    /* ui service treads might want to run at a urgent display (uncommon) */
    ANDROID_PRIORITY_URGENT_DISPLAY =  HAL_PRIORITY_URGENT_DISPLAY,

    /* all normal audio threads */
    ANDROID_PRIORITY_AUDIO          = -16,

    /* service audio threads (uncommon) */
    ANDROID_PRIORITY_URGENT_AUDIO   = -19,

    /* should never be used in practice. regular process might not
     * be allowed to use this level */
    ANDROID_PRIORITY_HIGHEST        = -20,

    ANDROID_PRIORITY_DEFAULT        = ANDROID_PRIORITY_NORMAL,
    ANDROID_PRIORITY_MORE_FAVORABLE = -1,
    ANDROID_PRIORITY_LESS_FAVORABLE = +1,
};
2. Communication b/w task in Bluedroid stack.

Ans: we are using _senmsg(data) API, inside this we are using the Message QUEUE to communicate between (b/w) the task.

3. Why does Bluetooth only allow 7 simultaneous slaves?

Ans: In a piconet, one master can actively communicate with seven other devices
(limited by a 3 bit address), and up to 255 devices can be part of the piconet but inactive("parked").

In the piconet, one or more slaves are connected to a single master. To identify each slave separately, each
slave is assigned a temporary 3 bit address to be used withn it is active.

Packets exchanged between the master and the slave carry the active member address of slave.
in other words, the address of the slave is used in both master and slave packets and in slave to master packets.
Slave that are disconnnected or parked, give up their address and a new one must be assigned when they re-enter the piconet.

The number of device that can be paired is practically unlimited- as long as you have enough

storage for every device's MAC address and link key.



---others---
Imp links:
1. http://www.cnblogs.com/JCSU/articles/1290373.html
2. http://www.techinterviews.com/c-interview-questions-and-answers

*****************************************************************************

1.How does bluetooth turn on? Explain the steps?
2.Tell anyone API which has been used in the framework from the lower level of stack?
3.Explain the code flow of the OPP profile?
4.Tell the file name of HAL which is used as the interface for your profile?
5.Explain the code flow in of btif,bta,jv,dm layer in bluedroid? How they interact?
6.In which layer is the state machine of the OPP profile exist?
7.Where is the L2cap layer code in the bluedroid stack?
8.How do you change the debugging level in the code?
9.How do the SDP works?
10.Tell the function name which is being called from the bt_sock.c to the corresonding RFCOMM and L2CAP file?

C Questions:
1.Why do you use the Volatile keyword?
2.Explain the storage class in C? Explain them?
3.Write the optimized code to delete a node which is 5th from the end? 
4.If a link list data part should contain all three int,char,float. Then how do you declare the linked list?
5.What is quick sorting? What is its worst and best case?
6.Explain the memory map?
7.Where the static,global,auto varible stored in the memory mapping?
8.What is the difference between inline function and MACRO?


OS questions:
1.How the scheduler works? How many types? Which is the best?
2.What is PCB? What does it store?
3.If a process wake up from the sleep which state it goes and what is the flow?
4.WHat is semaphore, mutex, spin lock? Explain the usage of them?

Wednesday, March 8, 2017

State codes of l2cap channels

These state codes indicate the state of an l2cap channel


Defines

#define CH_NOT_ASSIGNED   0x00
#define CH_CLOSED   0x01
#define CH_W4_L2CAP_CONNECT_RSP   0x02
#define CH_W4_L2CA_CONNECT_RSP   0x03
#define CH_CONFIG   0x04
#define CH_OPEN   0x06
#define CH_W4_L2CAP_DISCONNECT_RSP   0x07
#define CH_W4_L2CA_DISCONNECT_RSP   0x08


Bluetooth errors


0x01 Unknown HCI Command.
0x02 No Connection.
0x03 Hardware Failure.
0x04 Page Timeout.
0x05 Authentication Failure.
0x06 Key Missing.
0x07 Memory Full.
0x08 Connection Timeout.
0x09 Max Number Of Connections.
0x0A Max Number Of SCO Connections To A Device.
0x0B ACL connection already exists.
0x0C Command Disallowed.
0x0D Host Rejected due to limited resources.
0x0E Host Rejected due to security reasons.
0x0F Host Rejected due to remote device is only a personal device.
0x10 Host Timeout.
0x11 Unsupported Feature or Parameter Value.
0x12 Invalid HCI Command Parameters.
0x13 Other End Terminated Connection: User Ended Connection.
0x14 Other End Terminated Connection: Low Resources.
0x15 Other End Terminated Connection: About to Power Off.
0x16 Connection Terminated by Local Host.
0x17 Repeated Attempts.
0x18 Pairing Not Allowed.
0x19 Unknown LMP PDU.
0x1A Unsupported Remote Feature.
0x1B SCO Offset Rejected.
0x1C SCO Interval Rejected.
0x1D SCO Air Mode Rejected.
0x1E Invalid LMP Parameters.
0x1F Unspecified Error.
0x20 Unsupported LMP Parameter Value.
0x21 Role Change Not Allowed
0x22 LMP Response Timeout
0x23 LMP Error Transaction Collision
0x24 LMP PDU Not Allowed
0x25 Encryption Mode Not Acceptable
0x26 Unit Key Used
0x27 QoS is Not Supported
0x28 Instant Passed
0x29 Pairing with Unit Key Not Supported
0x2A-0xFF Reserved for Future Use.

Reference: http://www.btnode.ethz.ch/static_docs/old/support/btn_api/group__l2cap__channel__state__codes.html 

Thursday, October 15, 2015

Bluedroid Stack

Directory Structure  of Bluedroid in Android:



BLuedroid Folder Structure description:

a) audio_a2dp_hw/  -->  A set of audio interfaces for external audio module to inject their implementation of these audio interface.

b) bta/  -->  It is Bluetooth application profile layer, The btif will call bta.

c) btif/  --> All the Bluetooth JNIs will direct;ly intract with btif

d) conf/ --> Configuration files for bluedroid ( Ex. debugging level, path of snoop log)

e) embdrv/ ---> SBC encoder/decoder

f) gki/  --> Defines a tiny embedded os based on pthread, It means generic kernel interface

g) HCI/ --> Implementation for HCI ( Ex. To compose the HCI command and emit it)

h) main/ --> The core initialization function for the Bluedroid( Initialze OS/HCI etc

i) osi/ --> OS interface for gki, ( Ex. Alarm/queue/list)

j) stack/ --> the bluetooth core stack, Between BTA and HCI

k) test/ --> A test tool for bluedroid ( framework and command line test tool)

l) udrv/ --> Implementation for UIPC ( IPC)

m) utils/ --> HElper function for bludroid

n) vnd/ --> Implementation for vendor features, ( Android's BLE proprietary features)


------------------------------STACK-------------------------------------



BT IF – Bluetooth Interface layer:
Implements the HAL interfaces that are invoked by the JNI calls
Maintains the callbacks registered by JNI
JNI callbacks are invoked by the IF layer based on the updates from the BTA/Stack
 
BTA – Bluetooth Application Layer:

Implements the Bluetooth profiles 
Maintains the profiles state machines
Handles events from the Stack and sends it back to IF layer

Bluedroid Stack:
Implements all protocols

HCI Layer:
HCI layer built as a shared library (libbt-hci) and acts as an interface between the transport layer and the stack. 
Support for the HCI H4 or the SMD transport – glues the serial driver calls for instance, with the upper layers

-----------> Bluedroid component---<
Structure is split into the following parts 
Application Specific Layer
ex. contains Bluetooth APK and android Services for Profiles. 
Bluetooth Middleware components
 ex. Bluetoothheadsetservice  and JNI System Object (libbluetooth_jni) 
Bluetooth Profile Interface (BTIF)  and stack adaptation layer (BTA =>  libbt-brcm_bta system object)
Core Stack (libbt-brcm_stack) and HCI Transport interface (libbt-hci)
Kernel drivers for transport layers like Serial, USB, SDIO 
Real Physical Hardware  (SOC)


Bluedroid stack, profiles and application run in a single user space process “com.android.bluetooth”
Bluetooth code runs in the context of 4 Tasks
BTIF_TASK
BTU_TASK
A2DP_MEDIA_TASK
GKI_TIMER_TASK
Communication between the above tasks is through MESSAGE_QUEUE
// Example:
void BTA_DmSearch(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK services, tBTA_DM_SEARCH_CBACK *p_cback)
208{...
 bta_sys_sendmsg(p_msg);
}
571void bta_sys_sendmsg(void *p_msg)
572{
573    // There is a race condition that occurs if the stack is shut down while
574    // there is a procedure in progress that can schedule a task via this
575    // message queue. This causes |btu_bta_msg_queue| to get cleaned up before
576    // it gets used here; hence we check for NULL before using it.
577    if (btu_bta_msg_queue)
578        fixed_queue_enqueue(btu_bta_msg_queue, p_msg);
579}

API calls from JNI are transferred to BTIF_TASK context by posting messages
JNI/HAL callbacks run in the context of BTIF_TASK
BTIF Task intern will switch the context to BTU_TASK based on the request
Profile and Protocol implementation run in the context of BTU_TASK
Bluetooth transport driver has Rx thread to read data from UART/SMD (bt_hc_worker_thread)

Tuesday, October 13, 2015

Useful macro in Bluetooth

Device Type:
    * Bluetooth device type, Unknown
     */
    public static final int DEVICE_TYPE_UNKNOWN = 0;
    /**
     * Bluetooth device type, Classic - BR/EDR devices
    */
    public static final int DEVICE_TYPE_CLASSIC = 1;
    /**
     * Bluetooth device type, Low Energy - LE-only
    */
    public static final int DEVICE_TYPE_LE = 2;
    /**
     * Bluetooth device type, Dual Mode - BR/EDR/LE
    */
    public static final int DEVICE_TYPE_DUAL = 3;
/**
     * A bond attempt succeeded
     * @hide
     */
    public static final int BOND_SUCCESS = 0;
   /**
     * A bond attempt failed because pins did not match, or remote device did
     * not respond to pin request in time
     * @hide
     */
    public static final int UNBOND_REASON_AUTH_FAILED = 1;

    /**
     * A bond attempt failed because the other side explicitly rejected
     * bonding
     * @hide
     */
    public static final int UNBOND_REASON_AUTH_REJECTED = 2;

   /**
     * A bond attempt failed because we canceled the bonding process
     * @hide
     */
    public static final int UNBOND_REASON_AUTH_CANCELED = 3;

    /**
     * A bond attempt failed because we could not contact the remote device
     * @hide
     */
    public static final int UNBOND_REASON_REMOTE_DEVICE_DOWN = 4;

    /**
     * A bond attempt failed because a discovery is in progress
     * @hide
     */
    public static final int UNBOND_REASON_DISCOVERY_IN_PROGRESS = 5;

    /**
     * A bond attempt failed because of authentication timeout
     * @hide
    */
    public static final int UNBOND_REASON_AUTH_TIMEOUT = 6;

    /**
     * A bond attempt failed because of repeated attempts
     * @hide
     */
    public static final int UNBOND_REASON_REPEATED_ATTEMPTS = 7;

    /**
     * A bond attempt failed because we received an Authentication Cancel
     * by remote end
     * @hide
     */
    public static final int UNBOND_REASON_REMOTE_AUTH_CANCELED = 8;

/**
479     * The user will be prompted to enter a pin or
480     * an app will enter a pin for user.
481     */
482    public static final int PAIRING_VARIANT_PIN = 0;

    public static final int PAIRING_VARIANT_PASSKEY = 1;
489
490    /**
491     * The user will be prompted to confirm the passkey displayed on the screen or
492     * an app will confirm the passkey for the user.
493     */
494    public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = 2;
495
496    /**
497     * The user will be prompted to accept or deny the incoming pairing request
498     * @hide
499     */
500    public static final int PAIRING_VARIANT_CONSENT = 3;
501
502    /**
503     * The user will be prompted to enter the passkey displayed on remote device
504     * This is used for Bluetooth 2.1 pairing.
505     * @hide
506     */
507    public static final int PAIRING_VARIANT_DISPLAY_PASSKEY = 4;
508
509    /**
510     * The user will be prompted to enter the PIN displayed on remote device.
511     * This is used for Bluetooth 2.0 pairing.
512     * @hide
513     */
514    public static final int PAIRING_VARIANT_DISPLAY_PIN = 5;

Inquiry in Bluetooth after turn on BT

BT inquiry:

We are going to start form the scanning or inquiring the device, once the BT is turned ON.


/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothSettings.java:
This function is get called from the top right cornor where we are doing the refresh.
public boolean onOptionsItemSelected(MenuItem item) --> startScanning();

// this will get called when BT is totaly turned ON.
 public void onBluetoothStateChanged(int bluetoothState)--> startScanning();

// This function will get called when any device is getting bonded once the bonding complete then below content will
get updated.
public void onDeviceBondStateChanged(CachedBluetoothDevice cachedDevice, int bondState) --> startScanning();

 /packages/apps/Settings/src/com/android/settings/bluetooth/LocalBluetoothAdapter.java
startScanning()--> mAdapter.startDiscovery()

/frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java
 : Start the remote device discovery process. The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page
scan of each new device to retrieve its Bluetooth name.
It is asynchronous call, it will return immediately. Register for #ACTION_DISCOVERY_STARTED and ACTION_DISCOVERY_FINISHED intents to determin exactly when the disocvery starts and completes.
Register for BluetoothDevice#ACTION_FOUND to be notified as remote bluetooth devices are found.

NOTE: Discovery is not managed by th eActivity, but is run as a system service, so an application should always call BluetoothAdapter#cancelDiscovery().
Device discovery will only find remote device that are currently discoverable.
 mService.startDiscovery();

/packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java

startDiscovery() --> startDiscoveryNative();

 /packages/apps/Bluetooth/jni/com_android_bluetooth_btservice_AdapterService.cpp

startDiscoveryNative(JNIEnv* env, jobject obj) --> start_discovery();

/hardware/libhardware/include/hardware/bluetooth.h[HAL LAYER]

int (*start_discovery)(void);

/external/bluetooth/bluedroid/btif/src/bluetooth.c [STACK LAYER NOW ONWARDS]

static int start_discovery(void)--> btif_dm_start_discovery();

/external/bluetooth/bluedroid/btif/src/btif_dm.c

btif_dm_start_discovery-->   BTA_DmSearch(&inq_params, services, bte_search_devices_evt);

/external/bluetooth/bluedroid/bta/dm/bta_dm_api.c
// This function searches for peer bluetooth devices.It performs an inquiry and gets the rremote name for devices.

BTA_DmSearch()


/external/bluetooth/bluedroid/bta/dm/bta_dm_act.c
//Start an inquiry
bta_dm_search_start() --> BTM_StartInquiry()

/external/bluetooth/bluedroid/stack/btm/btm_inq.c
// for start the inquiry:
BTM_StartInquiry(), p_results_cb  -- is the pointer to callback with inquiry result.

NOTE: Inquiry having 3 second timeout waiting for response.

------------------- after inquiry complete sending data to application side------------------
/external/bluetooth/bluedroid/btif/src/btif_dm.c
//Switches context from BTE to BTIF for DM search events
bte_search_devices_evt()---> btif_dm_search_devices_evt()

/external/bluetooth/bluedroid/btif/src/btif_dm.c
btif_dm_search_devices_evt()-->
  HAL_CBACK(bt_hal_cbacks, device_found_cb,num_properties, properties);

  /hardware/libhardware/include/hardware/bluetooth.h[HAL layer]
device_found_callback device_found_cb;

/packages/apps/Bluetooth/jni/com_android_bluetooth_btservice_AdapterService.cpp
device_found_callback () -->devicePropertyChangedCallback()

/packages/apps/Bluetooth/src/com/android/bluetooth/btservice/JniCallbacks.java

devicePropertyChangedCallback () -->  mRemoteDevices.devicePropertyChangedCallback(address, types, val);


/packages/apps/Bluetooth/src/com/android/bluetooth/btservice/RemoteDevices.java

devicePropertyChangedCallback() -->

Bonding in Bluetooth ( Pairing )


Bonding in BT:

Once the device is get displayed on the device, after the inquiry then we will proceed
for the bonding. Then below function will get called when the user start then bonding procedure from device.


/packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothDevicePreference.java
//
private void pair() ---> mCachedDevice.startPairing()

/frameworks/base/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java
mDevice.createBond()

/frameworks/base/core/java/android/bluetooth/BluetoothDevice.java
// Start the bonding (pairing) process with the remote device. It is asynchronous call, it will return immediately.
Register for #ACTION_BOND_STATE_CHANGED intentes to be notified when the bonding process
completes, and its result.
public boolean createBond()

/packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java
// It will send event to BondStateMachine.CREATE_BOND
public boolean createBond(BluetoothDevice device, int transport)

1. /packages/apps/Bluetooth/src/com/android/bluetooth/btservice/BondStateMachine.java
[createBond()]--> mAdapterService.createBondNative(addr, transport):from here the call will go to the native. to create the bond.--> createBondNative();
2. same file : BONDING_STATE_CHANGE--> go for weather the current state is bonded, none, bonding.

 /packages/apps/Bluetooth/jni/com_android_bluetooth_btservice_AdapterService.cpp
sBluetoothInterface->create_bond()

3. /packages/apps/Bluetooth/src/com/android/bluetooth/btservice/AdapterProperties.java
onBondStateChanged()->  This function sahll be invoked from BondStateMachine whenever th bond sate changes.

4. /hardware/libhardware/include/hardware/bluetooth.h [HAL layer]
int (*create_bond)(const bt_bdaddr_t *bd_addr, int transport);

5. /system/bt/btif/src/bluetooth.c
static int create_bond(const bt_bdaddr_t *bd_addr, int transport)

6. /system/bt/btif/src/btif_dm.c
// It will post event #BTIF_DM_CB_CREATE_BOND.
bt_status_t btif_dm_create_bond(const bt_bdaddr_t *bd_addr, int transport)
// and the call will come to here
 btif_dm_cb_create_bond(&create_bond_cb->bdaddr, create_bond_cb->transport);
BTA_DmBondByTransport()
btif_hh_connect(bd_addr); // only for the HID device other wise for BR_EDR above call.

NOTE:
1. When the call will go to [btif_dm_cb_create_bond], it will call [bond_state_changed] and then
call will go to the application layer i.e bond state is changed not , from "bond_none" to bonding.


7. /system/bt/bta/dm/bta_dm_api.c
// It will initiates a bonding procedure with a peer device. and post the event: BTA_DM_API_BOND_EVT
BTA_DmBondByTransport() or BTA_DmBond()

8. /system/bt/bta/dm/bta_dm_act.c
void bta_dm_bond (tBTA_DM_MSG *p_data)

9. /system/bt/stack/btm/btm_sec.c[this file contain regarding securitypairing SSP adn link key]
// It perform bonding with peer device. If the connection is already up, but not secure, pairing
is attempted. If already paired BTM_SUCCESS is returned.
BTM_SecBondByTransport()--> btm_sec_bond_by_transport()
btm_sec_bond_by_transport --->This is bond function that will start either SSP or SMP
//This function is cllled to perform bonding with peer device. If connection is already up, but not secure,
pairing is attempted. If already paired BTM_SUCCESS is returned.
BTM_SecBond() --> btm_sec_bond_by_transport

btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ);
// IF the device matches with stored paring address reset the paring state to idle.
btm_sec_change_pairing_state(BTM_PAIR_STATE_IDLE);


10. /external/bluetooth/bluedroid/stack/btm/btm_sec.c

// This is bond function that will start either SSP or SMP.
btm_sec_bond_by_transport()

Bluetooth Turning ON

Once Phone Bootup is complete, then BT initilization will be go...com.android.bluetooth and com.btservice.AdapterService will get started.

1. Device supporting profile is get added to config.(like, a2dp, hid, pan,map,etc)
2. Register IBluetoothManagerCallback.
3. Init Bluedroid, Load bt_stack.conf and Start BTIF.
4. BluetoothServiceConnection
5. getAdapterPropertiesNative --> get_adapter_properties(at the time of init)
6. Adapterpropertychangedcallback with Set_adapter_property: address, Name.

*********************************************************************
User action: Enable BT(Tuning ON):
once the user turn on BT, the state will go from 10 to 11(turning on )
then it will start all the profile services (hidservice, a2dpservice...),then call will go for the enable BT to JNI-->HAL-->BTIF-->BTE-->HCI--> vendor specific--> UART.
btif will wait for th trigger to init chip and stack. This trigger will be received by btu_task once the UART is opened and ready.


Call flow of BT ON from the APP side:

1. /packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothEnabler.java
call-->  mLocalAdapter.setBluetoothEnabled(isChecked);
2. /packages/apps/Settings/src/com/android/settings/bluetooth/LocalBluetoothAdapter.java
call--> mAdapter.enable();
3.[BluetoothAdapter.java] return mManagerService.enable();
NOTE: 1. Show toast message : BT is not allowed in Airplane Mode.
4. [LocalBluetoothAdapter.java]private static final int SCAN_EXPIRATION_MS = 5 * 60 * 1000; // 5 mins
6. Once BT came to TURN ON then it will initilize or update the local profile objects.(a2dp or handsfree profile)
   call -->  updateLocalProfiles();
7. notifyAdapterStateChange()[AdapterState.java]--> This is responsible for the state change managment.

Saturday, August 8, 2015

Bluetooth Basic Concept

Link Controller:
The link controller implements the Blutooth baseband protocol.

In the Bluetooth system, the link manager uses the services of the link controller to implement the LMP(link Manger protocol).

CONCEPT:

1. Addresses: 
Each BT device is assigned a 48-bit address consisting of three parts: a 24-bit lower address part (LAP) and 8-bit uppder address part(UPA), and a 16-bit so called non-significant address part(NAP).LAP and UAP address parts are used in several places in the Baseband protocol. The 32-bit concatenation of the upper and lower address parts is also used and abbreviated as ULAP.

2. Channels:
The BT standerd uses a number of of diffeerent channels, located at different radio frequencies, to communicate data. Channel hopping, i.e. periodic switching between channels, is used to reduce the impact of other radio sources disturbing particular channels, and to enable the existence of multiple BT network in one area.

3. Clocks and slots:
The BT clock is a 28-bit counter with a clock cycle of 312us.BT communicate at the Baseband level is organised into time slot. Each slot has length of two clock cycle.

4. PACKETS:
BT communicateion at the Baseband level is packet-oriented. Anumber of different packet types of varying lengh and with varying error correction and detection facilites are defined. Packets occupy one, three, or five time slots.

5. PICONETS:
The master in a piconet determines slot timing, the channel hopping sequence, and slot allocation. Slave have to adjust to the master's parameters.

6. INQUIRY Procedure: The inquiry procedure enables devices to locate other devices in its vicinity. The inquiring device  build up a list of neighbouring devices.

7. PAGE Procedure: It enables devices to establish connection b/w each other. A device page scan mode to listen for packets. On hearing a page packet addressd to itself, the scanning device send a page response. Two more packets are exchanged before a link is fully set up.

NOTE: As the result of the page procedure, the scanning device becomes a slave in the paging device's piconet.

*** Master/slave switch:  Sometimes it may be necessary to switch roles in an existing connection, i.e a master may need to join a slave's piconet. Instead of using the page procedure again, they can agree (at the LMP level) to use the Baseband master/slave switch procedure.

8. ACL Links:
Packets on an Asynchronous connection -less link are sent in the next availabel slot. Since there can be contention for slots and transmission errors, they are not guaranteed to arrive within a certain time. Error correction adn detecetion together with flow control ensure though, that packets are eventually delivered, and that happens in the oreder they were sent. ACL links can therfore be compared to TCP internet connection.

An ACL link b/w two devices is established through using the page or master/slave switch procedure.  Normally there will only be one ACL link b/w two devices, but there might be a second with exchanged master/slave roles.

Each device can maintain up to fourteen ACL links: up to seven links to slaves in its own piconet, and up to seven links to master of the other piconets

9. SCO links:
Synchronuous connection-orinted links reserved time slot at regular interval. Packets are guaranteed to be sent in the next reserved slot. Error correcction and detection can be used, but flow control is not provided. If an uncorrected transmission error occurs, the packet is lost. SCO link are therfore best suited to real-time data link audio or video where a continous data flow is more important tath data correctness. SCO link might best be compared to ISDN connections.

Two devices can use an existing ACL link to agree on the parameters for the establishment of an SCO link. Each SCO link is associated with an underlying ACL link. there can be multiple SCO links per ACL, i.e. multiple SCO links b/w two devices. Each devices can have up to Three SCO links altogether.

10. Broadcast:
The master of a piconet has the ability to broadcast ACL packets to all its connected slaves, whereby flow control is not provided.

Broadcast is implemented as an additional ACL link, which is availabe by default and over which packets can only be sent but not received. As a slave, broadcast packets are received on the same ACL link as other packets from the current master.

11. Link timeouts:
According to the Baseband specification, a newly established ACL link needs to be verified by the exchange of initial (possibly empty) packets. If that does not happen within a timeout period of 32 slots, the link is removed and the link manager is notified through the new_connection_timeout callback

Also, if no packet is received from a device within a timeout period of 16000 slots (i.e. 20 seconds), the ACL link to that device is removed and the link manager is notified through the supervision_timeout callback

12. Receive buffers:
As there are only one ACL and one SCO receive buffer, no link identifiers are needed here.

An incoming packet is signalled through a rx_reg_loaded c
After a packet has been read and, if necessary, the payload has been copied, it can be removed from the buffer using a clear_rx_reg command.

13. Transmit buffers
Transmit buffer commands take as their second argument the ID of the ACL or SCO link that the targeted buffer is associated with.

To load a packet into a SCO or ACL transmit buffer, the following two operations are used. The packet type must fit the link type, and for ACL links, the maximum slot number must be adhered to. For ACL packets, the packet length must not be greater than the maximum length allowed for the packet type. For SCO packets, the packet length is implicit in the type. The actual payload is provided through a pointer.
After a packet has been sent and, in the case of ACL links, acknowledged successfully,

14. SCO link establishment:
SCO link parameters have to be agreed at the LMP level. Using the add_sco_link command, the link manager can then tell the link controller about the new link.

Two IDs must be provided: an unused SCO link ID for the new link, and a used ACL link ID that denotes the master or slave device to connect to.


************************************************************************

Generic Steps follow up after BT ON:

A: Inquiry: A device in a new environment will automatically initate an inquriy to discover what access pints are within its range.

B: Paging: A baseband procedure invoked by a device which results in synchronization of the device with the access point.

C: Link establishment: The LMP will now establish a link with the access point. If security mode 3, then pairing begins at this layer.

D: Service Discovery: The LMP will use the SDP (service discovery protocol) to discover what device are available.

E: L2CAP channel created : with information obtained from SDP a L2cap channel is created. this may be directly used by the application or by another protocol (eg. RFCOMM, AVCTP etc)

F: Pairing: begins her if the security mode 2. --> then it will ask for the pin and create the link key and share it with remote device.





Monday, July 27, 2015

                                                    Bluetooth



BT ON/OFF

When we will do the BT ON/OFF on the UI, the call will go to the BluetoothManagerService and it will register the
BluetoothAdapter in this state it will init the stack and load the config file etc.

then the call will go to BluetoothAdapterProperties, BT state will change from 10->11.

after then it will start all the profile severice( like a2dp, pbap, hfp,avrcp etc), after then BT state will change from 11->12.

Now we will go for the bonding of the device{ When Remote device start the bonding or try to connect with local device.

The call will come to (btif_dm.c file) it will change the state to (BT_BOND_sTATE_BONDING) -> HAL(bluetooth.h)[bond_state_changed_callback]-> JNI(com_android_bluetooth_btservice_AdapterService.cpp)[bond_state_changed_callback]-->Application (BondStateMachine.java)[ bondStateChangeCallback]

Then appllication will respond through the JNI and then it will go to the stack {bluetooth.c{create_bond}--> btif_dm.c(btif_dm_create_bond())

Then BTIF layer will get the PIN_Request event (BTA_DM_PIN_REQ_EVT-> btif_dm_pin_req_evt)--> HAL--> JNI-->Application{ setPin--> pinReplyNative}



L BT states:
10[STATE_OFF]- Indicate BT adapter is off.
11[STATE_TURNING_ON]- Indicated the local BT adapter is turning on. However local clients should wait for (@link #STATE_ON) before attempting to use the adapter.
12[STATE_ON]-Indicate the local BT adapter is on, and ready for use.{ Start BREDR Service, Set connectable, discoverable}
13[STATE_TURNING_OFF]- Indicates the local BT adapter is turning off. Local clients should immediately attempt graceful disconnection of any remote links.{ OnBluetoothDisable--> Stop BR-EDR services, clear connectable, discoverable}

M BT state introduce some more states:
14[STATE_BLE_TURNING_ON]-
15[STATE_BLE_ON]-
16[STATE_BLE_TURNING_OFF]-

Turning ON State: 10-->14-->15-->11-->12
Turning OFF State: 12-->13-->15-->16-->10

-------------------- Once the BT is on, now we are going to Connect the i.e for the BOnding:------------
State Machine for BOND:
CREATE_BOND=1
CANCLE_BOND=2
REMOVE_BOND=3
BODING_STATE_CHANGE=4
SSP_REQUEST=5
PIN_REQUEST=6
BOND_STATE_NONE=0
BOND_STATE_BONDING=1
BOND_STATE_BONDED =2




Bonding main file are:
btif_dm.c

Bond types:

1. BOND_TYPE_UNKNOWN
2. BOND_TYPE_PERSISTENT
3. BOND_TYPE_TEMPORARY
4. ENCRYPTED_BREDR
5. ENCRYPTED_LE



Questions:

1. When ACL connection will be initiated??
2. when link key will be stored and how??

Wednesday, March 13, 2013

Makefile in Linux

                         -----------------------MAKEFILE-----------------------------

A Makefile basically consists of :

1) Definitions of variables and functions,
   example: myshell=bash
2) Commensts:
   e.g. # converting postscript to pdf or what ever
3) Includes:
   e.g.- include Makefile.local
4) Rules:
   e.g. - %.pdf: %.ps; -@ps2pdf $<

-------------------------

**)Mind the tab key (<tab>) prefacing the commands past the fist line.

**)Use a semicolon to stuff muiltiple commands into one single lin, or a backslash to join split lines. (Refer Makefile1)

NOTE::
I. The at-sign (@) in front of the commnad prevents make from announcing the commands it's going to do.
II. If you don't tell make a target, it will simply do the first rule.
III. If you tell make multiple targets, it will do them all in order.

------------------------------------------------------------------
We can Combine multiple makefiles:

command in makefile(-include m/Makefile-l)

When make encounters an include-command, it will stop processing the current Makefile, read the included Makefile and then continue where it left off.

-----------------------------------------------------------
If we define a target socks twice it will give the warning mesage
Example:
socks: ; @echo get into left sock
socks: ; @echo get inot right sock
***While make it will give the warning messages z`       
***For remove the warning message we have to duplicate the colon:

socks:: ; @echo get into left sock
socks:: ; @echo get inot right sock
*** Now When we make this it will not give the error
Imp Note:

CXXSOURCES = basic_sample.cpp       # list of source files
CXXOBJECTS = $(CXXSOURCES:.cpp=.o)  # expands to list of object files


-----------------------------------Built-in fuctions------------------------------
1) $(subst from,to,text)     Replace from with to in text.
2) $(patsubst pattern,replacement,text)  Replace words matching pattern with replacement in text.
3) $(strip string) Remove excess whitespace characters from string.
4) $(findstring find,text)     Locate find in text.
5) $(filter pattern...,text)     Select words in text that match one of the pattern words.
6) $(filter-out pattern...,text)     Select words in text that do not match any of the pattern words.
7) $(sort list)     Sort the words in list lexicographically, removing duplicates.
8) $(dir names...)     Extract the directory part of each file name.
9) $(notdir names...)     Extract the non-directory part of each file name.
10) $(suffix names...)     Extract the suffix (the last dot and following characters) of each file name.
11) $(basename names...)     Extract the base name (name without suffix) of each file name.
12) $(addsuffix suffix,names...)     Append suffix to each word in names.
13) $(addprefix prefix,names...)     Prepend prefix to each word in names.
14) $(join list1,list2)     Join two parallel lists of words.
15) $(word n,text)     Extract the nth word (one-origin) of text.
16) $(words text)     Count the number of words in text.
17) $(wordlist s,e,text)     Returns the list of words in text from s to e.
18) $(firstword names...)     Extract the first word of names.
19) $(wildcard pattern...)     Find file names matching a shell file name pattern (not a `%' pattern).
20) $(error text...)     When this function is evaluated, make generates a fatal error with the message text.
21) $(warning text...)     When this function is evaluated, make generates a warning with the message text.
22) $(shell command)     Execute a shell command and return its output.
23) $(origin variable)     Return a string describing how the make variable variable was defined.
24) $(foreach var,words,text)     Evaluate text with var bound to each word in words, and concatenate the results.
25) $(call var,param,...)     Evaluate the variable var replacing any references to $(1),$(2) with the first, second, etc. param values.


-----------------------------------Automatic Variable----------------------------------

$@     The name of the target.
$%     The target member name, when the target is an archive member.
$<     The name of the first (or only) prerequisite.
$?     The names of all the prerequisites that are newer than the target, with spaces between them.

$^ $+   The names of all the prerequisites, with spaces between them. The value of $^ omits duplicate prerequisites, while $+ retains them and preserves their order.
$*     The stem with which an implicit rule matches.
$(@D)
$(@F)     The directory part and the file-within-directory part of $@

$(*D)
$(*F)     The directory part and the file-within-directory part of $*

$(%D)
$(%F)     The directory part and the file-within-directory part of $%

$(<D)
$(<F)     The directory part and the file-within-directory part of $<

$(^D)
$(^F)     The directory part and the file-within-directory part of $^

$(+D)
$(+F)     The directory part and the file-within-directory part of $+

$(?D)
$(?F)     The directory part and the file-within-directory part of $?















Monday, February 11, 2013

Malloc, calloc, and Realloc

                              Calloc, malloc, free, realloc
                               -------------------------------------------
void *calloc(size_t nmemb, size_t size);
Calloc allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. if nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
** the memory is initialized to zeros.

void *malloc(size_t size);
allocates size bytes and returns a pointer to the allocated memory (BLOCK). The memory is neot cleared. If size is 0, then malloc() returns either NULL or a unique pointer value that can later be successfully passed to free().
** The memory is uninitialized.

Ex1:
int *ptr;
ptr=(int*) malloc(sizeof(int));

Ex2.
struct employee *ptr;
ptr=(struct employee *ptr)malloc (sizeof(struct employee));

void free( void *ptr);
free() frees the memory space pointed to by ptr, which must have been returned by a prevoious call to malloc(), caloc() or realloc(). otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is NULL, no operation is performed.

void *realloc ( void *ptr, size_t size)
realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly alllocated memory will be uninitialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to sero, and pt is not NULL, then the call is equivalent ot free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc or realloc(). If the area pointed to was moved, a freeptr) is done.
------------------------------------------------------------------------------------------------------------------------

Thursday, February 7, 2013

How to use GDB debugger

                                 -------------------GDB-----------------------------

1. gcc -g program.c
2. gdb ./a.out
3. break main
4. run
5. list ( show the all line of the program.c)
6. list 5,10 ( show the line form 5 to 10 )
7. bt ( back trace )
8. whatis variable_name (it will give the datatype of variable)
9. bt n ( print only the innermost n frames)
10. bt -n ( print only the outermost n frames)
11. fn ( select frame number n)
12. f addr ( select the frame at address addr)
13. up n ( move n frames up the stack )
14. down n ( move n frames down the stack )
15. info f ( print info about the frame )
    info b ( to list the number of breakpoints )   
16. break function ( Set a breakpoin at entry to function)
17. break -offset, break +offset ( set a break point some number of lines forward or backward to the position)
18. break linenum ( set the breakpoint at particular linenumber)
19. break filename:linenum ( set a breakpoin at line linenum in sourece file filename)
20. delete <breakpoint_number>
    clear <function>
21. Enable/Disable breakpoints
    a) enable <breakpoint_number>
    b) disable <breakpoint_number>
22. print $bpnum ( It will give the number of break points
23. watch expr (set a watchpint for an exeression. gdb will break when    expr is written into by the program and its value changes.
23. rewatch expr ( set a watchpoint that will brea when watch expr is read by the program.
24. awatch   ---()
25. info  watchpoint

26. continue[ignore-count] ( REsume program execution, at the address where your program last stopped. The optional argument ignore-count allows you to specify a further numbe ro ftimes to ignore a breakpoint at this location.

27. step [count]
    Continue running your program until control reaches a different source line, then stop it and return control to GDB.With the optional argument, it wil continue running as in step, but do so count times.
   
28. next[count]
    Continue to the next sourece line in the current( innermost) stack frame. This is similar to STEP, but function alls that appear within the line of code are executed without stopping . An optional argument count is a repeat count.
   
29 . finish ( continue running until just after function in the selected stack frame returns. Print the returned value( if any).

30. until ( continue running until a source line past the current line, in the current stack frame, is reached. This command is used to avoid single stepping throught a loop mor than once.

31. jump linespec ( Resume execution at line linespec. Execution stops again immediately if ther is a break ping there.

32. jump *address ( Resume execution at the instruction at address .
33. info local ( Show the
34  info reg ( Show all the machine register )

************************************************************************
**) SEGMENTATION FAULT:: It is often caused by trying to access a memory location that is not in the address space of the process.
**) BUS ERROR :: It is typically caused by trying to access an object with an improperly aligned address. (Ex: tring to fetch an int from address 1)
**) ILLEGAL INSTRUCTION:: It is typically occurs when execution branches into data. This sometimes happens when the stack is overwritten.
**) Arithmetic exception :: It is typically caused by integer  division by zero.

*************************************************************************
            LAUNCHING GDBSERVER IN TARGET PLATFORM:
    
     TCP/Ip
     1. gdbserver host:port <application name >
        example gdbserver 10.102.68.51:1233 hello
     2. COM port
        gdbserver commdevice <application name >
        example gdbserver /dev/com1 telephony

    LAUNCHING GDB IN HOST PLATFORM
  
   1. gdb telephony
   2. target remote /dev/com1
        OR
   1. (gdb)target remote <targetip>2345
   (gdb) continue (don't run once again. it is already running in target machine ).

  

Monday, February 4, 2013

SED and AWK command in Linux



-------------------AWK--------------------
1) Pattern scanning and text processing language


awk one-liner Tips

Print column1, column5 and column7 of a data file or output of any columns list

$awk ‘{print $1, $5, $7}’ data_file

$cat file_name |awk ‘{print $1 $5 $7}’

$ls –al |awk ‘{print $1, $5, $7}’ -- Prints file_permissions,size and date

Syntax of running an awk program

Awk ‘program’ input file(s)


List all files names whose file size greater than zero.

$ls –al |awk ‘$5 > 0 {print $9}’


List all files whose file size equal to 512bytes.

$ls –al |awk ‘$5 == 0 {print $9}’

print all lines

$awk ‘{print }’ file_name

$awk ‘{print 0}’ file_name

Number of lines in a file

$awk ‘ END {print NR}’ file_name

Number of columns in each row of a file

$awk ‘ {print NF’} file_name

Sort the output of file and eliminate duplicate rows

$awk ‘{print $1, $5, $7}’ |sort –u

List all file names whose file size is greater than 512bytes and owner is "oracle"

$ls –al |awk ‘$3 == "oracle" && $5 > 512 {print $9}’

List all file names whose owner could be either "oracle" or "root"

$ls –al |awk ‘$3 == "oracle" || $3 == "root" {print $9}’

list all the files whose owner is not "oracle

$ls –al |awk ‘$3 != "oracle" {print $9}’

List all lines which has atlease one or more characters

$awk ‘NF > 0 {print }’ file_name

List all lines longer that 50 characters

$awk ‘length($0) > 50 ‘{print }’ file_name

List first two columns

$awk ‘{print $1, $2}’ file_name

Swap first two columns of a file and print

$awk ‘{temp = $1; $1 = $2; $2 = temp; print }’ file_name

Replace first column as "ORACLE" in a data file

$awk ‘{$1 = "ORACLE"; print }’ data_file

Remove first column values in a data file

$awk ‘{$1 =""; print }’ data_file

Calculate total size of a directory in Mb

$ls –al |awk ‘{total +=$5};END {print "Total size: " total/1024/1024 " Mb"}’

Calculate total size of a directory including sub directories in Mb

$ls –lR |awk ‘{total +=$5};END {print "Total size: " total/1024/1024 " Mb"}’

Find largest file in a directory including sub directories

$ls –lR |awk ‘{print $5 "\t" $9}’ |sort –n |tail -1

$ awk -F":" '{ print $1 $3 }' /etc/passwd

$ awk -f myscript.awk myfile.in


------------------SED---------------------
1)  Stream editor for filtering and transforming text
2) Sed works as filter, which makes it particularly useful for scripts, sed works line oriented. The most simple commands are a pattern and an action . if no pattern is given, then action is applied to all lines, otherwise it is applied only to lines matching the pattern.

EXAMPLE::
1) A sample application of sed would be to delete the first 10 lines of stdin and echo the rest to stdout:

$cat /etc/passwd| sed -e '1,10d'

2) If we wanted to print only the first ten lines, we would have deleted all the lines starting with 11:

$cat /etc/passwd| sed -e '11,$d'

3)Another way to get only the first 10 lines is to use the -n option:

$cat /etc/passwd | sed -n -e '1,10p'

4)Commands in sed programs are separated by new lines. So if we wanted to delete the lines 1 to 4 and 6 to 9, we could use:

$cat /etc/passwd | sed -e '1,4d 
6,9d'

5)If we want to put command in the script files instead of using the command line.

$sed -f program.sed

















Wednesday, January 23, 2013

Working with Pulse Audio with Alsa

After Integration/Installation of Alsa and Pulse Audio We have to follow the following steps to play and record mp3 files.

Also we have set some configuration in the default.pa file

For setting the volume using pulseaudio::
$pacmd set-sink-volume 0 65537 (volume full)

For setting the volume to the mute::
$pacmd set-sink-mute 0 0 (volume)

This command put all the error and message into the file(cfg.out)
$ ./configure --help 1> cfg.out  2>&1

This command is used for the starting the pulseaudio binary file or we can say the server.
$pulseaudio --start --log-target=syslog --exit-idle-time=-1 (for run the pulseaudio)

This command is used for the recording of the .wav file using the pulseaudio
$gst-launch pulsesrc ! audio/x-raw-int,rate=8000,channels=1,width=16 ! queue ! audioconvert ! wavenc ! filesink location=/home/root/audio/far_from_love.wav

This command is used to play the mp3 file using the alsa it is not using the pulseaudio.
$gst-launch-0.10 filesrc location=/home/root/audio/far_from_love.mp3 ! mad ! alsasink

This command is used to play the mp3 file using the pulseaudio.
$gst-launch-0.10 filesrc location=/home/root/audio/far_from_love.mp3 ! mad ! pulsesink

This command is used for the recording of .wav file using the alsa .
$arecord -vv -fdat foo.wav

This command will set the Pulse input
$export PULSE_SOURCE=alsa_input.dsnoop

This command will give the list of alsa input/output cards
$LANG=C pactl list | grep -A2 'Source #' | grep 'Name: ' | cut -d" " -f2

This command will record the .mp3 file
gst-launch-0.10 pulsesrc device=alsa_input.hw_0_0 ! lame ! filesink location=sample.mp3

Qualcomm Short Term

  113 is the SL. 1st Target by mid July.

Total Pageviews