Sunday, June 12, 2022

How to recover dropped git stash

1. Get list of the stashes:

     git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP

2. Find needed commit_hash in the list

3. Run >git stash apply <commit_hash>


Tuesday, April 6, 2021

Ubuntu: How to disable unused microphone devices


  •     sudo apt install pavucontrol
  •     Launch pavucontrol
  •     Go to the "Configuration" tab at the very right
  •     Disable your webcam's microphone by choosing "Off" from the dropdown menu.



Monday, January 28, 2019

gtest: how to run tests many times until failure occured?

To run tests N times until failure occured, next command line:

<path_to_tests> --gtest_repeat=<N> --gtest_break_on_failure

Wednesday, August 30, 2017

VBoxClient high CPU usage issue



Having virtualbox version 5.0.6 r103037 I've faced with high CPU usage issue by VirtualBox instance with Ubuntu 14.04.

I've checked the CPU usage by top command and found that most of CPU periodically was used by
/usr/bin/VBoxClient --draganddrop. This process wasn't in the top of the list constantly, it appeared in the top periodically, kind of every second second for a while. However, due to this behavior CPU was very hot and I didn't like the noise of the coolers, besides it undermined the overall performance of the system.

I've looked for solution on different forums, stackoverflow and most of them claimed that this should be the issue with disabled HardwareAcceleration, but it was enabled in my case. Some people said that their problem was solved by reinstalling VboxGuestAdditions, but it didn't look like the case.

Then I've found article https://www.virtualbox.org/wiki/DnDDebug which described the problems with DragAndDrop feature. After that I decided simply to turn it off and look whether something would change:



To my surprise /usr/bin/VBoxClient --draganddrop process immediately stopped consuming a lot of CPU and issue was fixed.








Monday, August 28, 2017

Useful linux commands

Grep files with specified extension in directory recursively:
grep -R --include \*.h --include \*.cpp "Bar::foo()" ~/repo/

Display size of files/directories in current directory including hidden files and sort them by size increasing:
find . -maxdepth 1 -exec du -sh "{}" \; | sort -h

Update existing symbolic link path:
ln -sfn <directory_or_file> <symbolic_link>

Print only list of files in current directory and sort them by name:
ls -p | grep -v / | sort

Monitor virtual memory usage:
watch -n 5 free -m

Redirect to stderr and stdout to file:
./application  &>file


Run command multiple times:

for i in {1..10}; do command; done
Checkout changed files
 
git diff --name-only HEAD~ | xargs git checkout HEAD~ --

Saturday, August 13, 2016

C++ How to make cross-cast correctly?

Lets take a look at first, what is cross-cast:

Steps made by dynamic_cast 


Lets consider next conversion:
Source* ptr = new Actual(); 
Target* t = dynamic_cast<Target*>(ptr);

There are three steps in performing a dynamic cast. 
1. Finding the type and address of the Actual object given the Source pointer (ptr).
2. Determining if the Actual object derives unambiguously from the Target class. 
    If it does not, null is immediately returned. 
3. Computing the offset of the Target class within the Actual class to return a pointer to a Target object.

Conclusion

Cross-casting of pointers in C++ can be done in 3 ways:
 - using dynamic_cast;
 - using reinterpret_cast (can be done, but result pointer will be incorrect);
 - using C-style cast (can be done, but result pointer will be incorrect);
So, there is only one correct way of doing cross-casting in C++ is to use dynamic_cast.

References


C++ What does static_cast can do?

The behavior of static cast is well described in many sources. Below is the code example that could reveal some usage cases.
The output of the program execution is the next:

static_cast<int>(1.0) = 1
static_cast<int>(0xFFFFFFFFU) = -1
static_cast<int>(0xFF11FFFFFFULL) = 0x11FFFFFF
static_cast<float>(5) = 5.000000
static_cast<unsigned int>(-1) = 4294967295
(d1.*d1_func_ptr)() returns 1
(d12.*d12_func_ptr)() returns 2
(d12.*d12_func_ptr)() returns 1
(d1.*d1_func_ptr)() returns 2 

Sunday, March 13, 2016

Arduino UNO: why uploading sketch hangs?

I've faced with this issue recently and found that avrdude process that responsible for uploading sketch hasn't been finishing for a long time.
After digging into the issue I've found that it happens because TX/RX pins are connected.
After disconnecting last ones uploading started to work correctly.

Hope it will help.

Thursday, November 12, 2015

How to replace string in all files recursively on Linux?

Next Linux command replaces string 'old_data' by string 'new_data' in all files in current directory on Linux:

find . -type f -exec sed -i 's/old_data/new_data/g' {} +

Friday, October 23, 2015

boost.python: how to bind member overloaded functions which semantic differs only by const?

Lets suppose we have class Test that we want export to python:
class CustomType
{
public:
    int m_value;
};

class Test
{
public:
    const CustomType & get_value() const { return m_value; }
    CustomType & get_value() { return m_value; }

private:
    CustomType m_value;
};
The piece of code that is below binds both overloads of get_value method:
void add_python_bidings_test( )
{
    class_< Test >( "Test" )
        .def( "get_value_const", ( const CustomType & (Test::*)() const) &Test::get_value,
        boost::python::return_value_policy<boost::python::copy_const_reference>( ))
        .def( "get_value", ( CustomType & (Test::*)() ) &Test::get_value,
        boost::python::return_value_policy<boost::python::copy_non_const_reference>( ) );
}
I compiled this only on Visual Studio compiler and didn't check inside python, however, I believe it should work. Please, let me know if you find any issues.

Wednesday, September 30, 2015

Windows installer has encountered an unexpected error installing this package. The error code is 2502.

I've faced with this error during installing FAR manager on Windows 8.1.
The issue has been fixed by executing next steps:
  1. Run as administrator cmd.exe.
  2. > cd %USERPROFILE%/Downloads
  3. > far2.x86.msi

I believe there is a better way to resolve this issue.
I'll share it with you as soon as find it.

Tuesday, January 27, 2015

How does processor use stack?

Processor uses stack for saving registers or other data between switching of execution context. For architecture IA-32, IA-64 CPU uses stack in next instructions:

1. CALL and RET 
CALL instruction saves procedure related data on the stack and branches to the called procedure specified using the target operand. The target operand specifies the address of the first instruction in the called procedure. 

RET instruction transfers program control to a return address located on the top of the stack. The address is usually placed on the stack by a CALL instruction, and the return is made to the instruction that follows the CALL instruction.

2. ENTER and LEAVE
ENTER instruction creates a stack frame for a procedure.

LEAVE instruction releases the stack frame set up by an earlier ENTER instruction.

3. INT, INTO and IRET/IRETD
The INT n instruction generates a call to the interrupt or exception handler specified with the destination operand. INTO instruction is a shortcut for INT 4 instruction which means calling overflow exception handler.

IRET/IRETD instruction returns program control from an exception or interrupt handler to a program or procedure that was interrupted by an exception, an external interrupt, or a software-generated interrupt. These instructions are also used to perform a return from a nested task.
 
4. PUSH, PUSHA/PUSHAD, PUSHF/PUSHFD
PUSH instruction decrements the stack pointer and then stores the source operand on the top of the stack.

PUSHA/PUSHAD pushes the contents of the general-purpose registers onto the stack.

PUSHF/PUSHFD pushes EFLAGS register onto the stack.
 
5. POP, POPA/POPAD
POP instruction loads the value from the top of the stack to the location specified with the destination operand (or explicit opcode) and then increments the stack pointer. The destination operand can be a general-purpose register, memory location, or segment register.

POPAD instruction pops doublewords and POPA pops words from the stack into the general-purpose registers. The registers are loaded in the following order: EDI, ESI, EBP, EBX, EDX, ECX, and EAX (if the operand-size attribute is 32) and DI, SI, BP, BX, DX, CX, and AX (if the operand-size attribute is 16). (These instructions reverse the operation of the PUSHA/PUSHAD instructions.) The value on the stack for the ESP or SP register is ignored. Instead, the ESP or SP register is incremented after each register is loaded.

All descriptions of commands is taken from "Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volumes 2A, 2B & 2C", please check it for more details.

Thursday, January 15, 2015

How to prevent starting another bash script copy?

Usually pidfile is used in order to check if bash script has been already started. If pidfile exists and its content is valid then it means that script has been already started and its second instance exits. If pidfile doesn't exist or it stores invalid PID file it means that script is stopped, so script instance continue to run. Looks like nothing complex, but there is one pitfall. 

If script has been started simultaneously (for example: ./script& ./script&) race condition can happen: both scripts will check that pidfile doesn't exist and then write its PID values to the pidfile. As the result, only last PID value will be stored in the pidfile and both instance will continue to run.

In order to prevent race condition file should be created atomically. 
Below is the example how to do it.


set -C - enable preventing redirection to already existing files;
set +C - disable preventing redirection to already existing files;

You also can notice that echo $$ > $g_sPathToPidFile is surrounded by brackets {}.
It is not the coincidence, these brackets prevent script from printing error "cannot overwrite existing file" to stdout in case if pidfile has been already created.

Pay attention I've tested set -C command behavior only for /bin/bash interpreter.

Sunday, January 11, 2015

Is critical section a kernel object on Windows?

The answer is no, however, Windows creates event inside critical section object when a thread tries to acquire the object, but is blocked by another thread. The event is used in order to notify a blocked thread that the critical section object has been released and can be acquired again.

Thursday, December 18, 2014

What is the difference between mutex and critical section on Windows?

There are main differences between mutex and critical section on Windows:
  1. Mutex is a kernel object. Critical section is implemented with using interlocked operations and in rare cases it uses event.
  2. In most cases critical section doesn't require switches from user mode to kernel mode, that is why it is much faster than mutex in general.
  3. Mutex can be used for synchronization of threads between different processes, but critical section can't be.
  4. Mutex can be named, but critical section can't be.
  5. Thread can wait for a mutex with using timeout, but when it is locked on critical section then timeout parameter doesn't supported.

Tuesday, December 9, 2014

Why do I get this error LNK2019: unresolved external symbol __malloc_dbg referenced in function?

I've faced with the same issue several minutes ago.
It has happened because I had set /MT by mistake instead of /MTd:

It was:


but it should be:

Monday, November 10, 2014

What is the purpose of universal hashing?


Suppose you are participating in programming competition. The task for you is to write a hash function that will process an input data as fast as possible. You can see and test other programmers' solutions as well as they can see your source code and generate the worst-case input. The winner is the programmer who will write the fastest hash function.

Problem is that any fixed hash function is vulnerable to such terrible worst-case behavior. Even if you write sophisticated hash function it will be possible to choose n keys that all hash to the same slot, so complexity of searching in average case will be O(n) instead of O(1).

Instead of writing sophisticated hash functions you might pay attention to randomness. Randomness not in the implementation of hash function, but in choosing hash function from set of multiple hash functions.

The approach when hash function is choosing randomly in a way that is independent of the keys that are actually going to be stored is called universal hashing.

So, purpose of universal hashing is to eliminate the vulnerability that can be used to slow down your program execution.

Wednesday, September 10, 2014

How to use shared memory for process intercommunication on Linux?

On Linux intercommunication with using shared memory API is more elegant than on Windows.

Shared memory server


Example sequence of calls for shared memory server is:
  1. Call ftok function and receive key for shared memory segment.
  2. Call shmget with IPC_CREAT to create new shared memory segment.
  3. Call shmat to attach to shared memory array. Do some operations with shared memory.
  4. Call shmdt to detach from shared memory array.
  5. Call shmctl with IPC_RMID to remove shared memory segment.
Here is an example of shared memory server which writes Hello World message to shared memory and waits for pressing of any key:

#include <stdio.h>

#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <cstring>
#include <fcntl.h>

int main(int argc, char ** argv)
{
        key_t key = ftok(argv[0], 1);
        if (key < 0)
        {
                perror("ftok"); /*Displays the error message*/
                return -1;
        }

        printf("Key for shared memory: '%s'\n", argv[0]);

        int shmid = shmget(key, 4096,  IPC_CREAT | O_EXCL | S_IRUSR | S_IWUSR);
        if(shmid == -1)
        {
                fprintf(stderr, "Failed to create memory segment. %s\n", 
                        strerror(errno));
                return -1;
        }

        void * pAddr = shmat(shmid, NULL, 0);
        if((long long )pAddr == -1)
        {
                if(shmctl(shmid, IPC_RMID, NULL) == -1)
                {
                        fprintf(stderr, "Failed to remove shared memory segment. %s\n", 
                                strerror(errno));
                        return -1;
                }

                fprintf(stderr, "Failed to attach to shared memory. %s\n", 
                        strerror(errno));
                return -1;
        }

        const char * szcServerMessage = "Hello world!";
        strcpy((char *) pAddr, szcServerMessage);

        printf("Server put message to shared memory.\n");
        printf("Press any key for exit ...\n");
        getchar();

        if(shmdt(pAddr) == -1)
        {
                fprintf(stderr, "Failed to detach from shared memory segment. %s\n", 
                        strerror(errno));
                return -1;
        }

        if(shmctl(shmid, IPC_RMID, NULL) == -1)
        {
                fprintf(stderr, "Failed to remove shared memory segment. %s\n", 
                        strerror(errno));
                return -1;
        }

        return 0;
}

Shared memory client

Example sequence of calls for shared memory client is:
  1. Call ftok function and receive key for shared memory segment.
  2. Call shmget to obtain pointer to existing shared memory segment descriptor.
    Don't set IPC_CREAT flag, besides instead memory size you can simply pass 0.
  3. Call shmat to attach to shared memory array. Do some operations with shared memory.
  4. Call shmdt to detach from shared memory array.
Please notice that on client side you shouldn't call shmctl with IPC_RMID, because shared segment was created on server side, but not on client.

Here is implementation of shared memory client that attaches to the shared memory segment and then reads message:

#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <cstring>
#include <fcntl.h>

int main(int argc, char ** argv)
{
        key_t key = ftok("./server", 1);
        if (key < 0)
        {
                perror("ftok"); /*Displays the error message*/
                return -1;
        }

        int shmid = shmget(key, 0,  S_IRUSR | S_IWUSR);
        if(shmid == -1)
        {
                fprintf(stderr, "Failed to create memory segment. %s\n", 
                        strerror(errno));
                return -1;
        }

        void * pAddr = shmat(shmid, NULL, 0);
        if((long long )pAddr == -1)
        {
                fprintf(stderr, "Failed to attach to shared memory. %s\n", 
                        strerror(errno));
                return -1;
        }

        char szcBufferMessage[4096];
        strcpy(szcBufferMessage, (char *) pAddr);

        printf("Client read message from shared memory: %s \n", szcBufferMessage);
        printf("Press any key for exit ...\n");
        getchar();

        if(shmdt(pAddr) == -1)
        {
                fprintf(stderr, "Failed to detach from shared memory segment. %s\n", 
                        strerror(errno));
                return -1;
        }

        /* In client we shouldn't delete any segment, because it is allocated by server */

        return 0;
}

Server's output example:

$ ./server
Key for shared memory: './server'
Server put message to shared memory.
Press any key for exit ...

Client's output example:

$ ./client
Client read message from shared memory: Hello world! 
Press any key for exit ...

As you can see client successfully reads the message from server.
Hope this post is useful. Good luck!

Friday, September 5, 2014

How to use shared memory for process intercommunication on Windows?

Introduction
Shared memory is the fastest way for process intercommunication. In the other hand it is the most danger. One mistake in code will crash your program at once.

Shared memory server
Here is an example of shared memory server that allocates shared memory and writes there a message.
#include <windows.h>
#include <conio.h>
#include <stdio.h>

const unsigned int c_uiSharedMemorySegmentSize = 512;

const char * szcSharedMemorySegmentName = "Global\\HelloMessage";

int main()
{
 printf("Shared memory server has been started successfully.\n");

 HANDLE hMapFile = CreateFileMapping(
    INVALID_HANDLE_VALUE,   // use paging file
    NULL,       // default security
    PAGE_READWRITE,     // read/write access
    0,        // maximum object size (high-order DWORD)
    c_uiSharedMemorySegmentSize, // maximum object size (low-order DWORD)
    szcSharedMemorySegmentName); // name of mapping object

 if (hMapFile == NULL)
 {
  fprintf(stderr, "Could not create file mapping object (%d).\n", GetLastError());
  return 1;
 }

 char * pcBuf = (char *) MapViewOfFile(hMapFile,   // handle to map object
  FILE_MAP_ALL_ACCESS, // read/write permission
  0,
  0,
  c_uiSharedMemorySegmentSize);

 if (pcBuf == NULL)
 {
  fprintf(stderr, "Could not map view of file (%d).\n", GetLastError());
  CloseHandle(hMapFile);
  return 2;
 }

 // Set memory for child process
 const char * szcMessageHelloWorld = "Hello world!";
 strcpy(pcBuf, szcMessageHelloWorld);

 printf("Message has been written to shared memory segment.\n");
 printf("You can start the client to read it.\n");
 printf("Press any key to remove shared memory segment and exit ...\n");

 getch();

 UnmapViewOfFile(pcBuf);

 CloseHandle(hMapFile);

 return 0;
}

Shared memory client
Here is an example of shared memory client that attaches to the shared memory and reads the message from the server.
#include <windows.h>
#include <stdio.h>
#include <conio.h>

const unsigned int c_uiSharedMemorySegmentSize = 512;
const char *  szcSharedMemorySegmentName = "Global\\HelloMessage";

int main()
{
 printf("Shared memory client has been started.\n");
 printf("Press any key to read the message from shared memory.\n");
 getch();

 HANDLE hMapFile = OpenFileMapping(
     FILE_MAP_ALL_ACCESS,   // read/write access
     FALSE,       // do not inherit the name
     szcSharedMemorySegmentName); // name of mapping object

 if (hMapFile == NULL)
 {
  fprintf(stderr, "Could not open file mapping object (%d).\n", GetLastError());
  return 1;
 }

 const char * pcBuf = static_cast<char *> (MapViewOfFile(hMapFile, // handle to map object
  FILE_MAP_ALL_ACCESS,           // read/write permission
  0,
  0,
  c_uiSharedMemorySegmentSize));

 if (pcBuf == NULL)
 {
  fprintf(stderr, "Could not map view of file (%d).\n", GetLastError());
  CloseHandle(hMapFile);
  return 2;
 }

 printf("Message from shared memory server: '%s'\n", pcBuf);
 printf("Press any key to exit ...");
 getch();

 UnmapViewOfFile(pcBuf);
 CloseHandle(hMapFile);

 return 0;
}
After you successfully built both examples you can start server at first:

Then start shared memory client and press any key:

As you can see client successfully reads the message from server.

Hope this post is useful. Good luck!


Thursday, September 4, 2014

How to do performance profiling of server process on Linux?

Suppose you have a server process on Linux and you want to investigate its performance.
To do performance profiling you need to run your server with using valgrind:

valgrind --tool=callgrind --dump-instr=yes --simulate-cache=yes --collect-jumps=yes ./path_to_server arg1 arg2

After you started the server you needed to wait some time while your server processed data.
As soon as data has been processed you may stop server.
As the result valgrind should generate file(s) with names like that: callgrind.out.58575.

Now the biggest part of job has been done already.
Next step is to open generated callgrind.out.* file(s) by using kcachegrind.

If you are interested in performance profiling child processes I'll bring you good news.
You can achieve it just by adding --trace-children=yes argument to valgring command line:

valgrind --tool=callgrind --dump-instr=yes --simulate-cache=yes --collect-jumps=yes --trace-children=yes ./path_to_server arg1 arg2

Hope this post is helpful. Good luck!