Collaborative C/C++ Extended Development Guide (1): Memory Security

  coroutine, php, swoole

The appearance of SWOLE 4 coprocessor has changed PHP from serial mode to concurrent mode. There are many PHP’sC/C++Extension failed to consider concurrency during development,ReentryProblems, resulting in unable to inSwooleUsed in coordination. This article will explain in detail how to write coordination concurrent securityC/C++Code.

Reentry

Sample code:

int t;
 
 void test1(int *x, int *y) {
 t = *x;
 *x = *y;
 //there may be synergetic switching in //fun1 function
 fun1();
 //Error Code
 *y = t;
 }
  • tIs a global variable orstaticStatic variable
  • In the coordination processACalled intest1Function, using global variablest
  • When called within a functionfun1()If there is a synergetic switch in this function, then if there is another synergetic switchBAlso implementedtest1Function, thentThe value of may be modified
  • coroutineBWhen suspended, return to the coordination processAAt this time*y = t, will get an incorrect value

Reference stack memory

This is also a serious risk point. coroutine1Sending the pointer of its own stack memory to another coprocessor2, association1When exiting, the synergetic stack memory will be released. coroutine2The life cycle of is longer than that of1, continue to read and write this memory, will result insegment fault.

Examples:

void co1() {
char buf[2048];
//Here, a new synergetic process is started. buf is the memory on the synergetic process 1 stack
co2(buf);
//when coprocessor 1 exits, stack memory will be released
}

void co2(char *buf) {
for(int i=0;   i<2048;  i++) {
Coroutine::sleep(1);
//buf memory may have been released here
buf[i] = 1;
}
}

Coordination safety code

In order to ensure safety, inSwoole4In synergetic programming:

  • Do not usestaticVariables and global variables, adhere to only local variables
  • If global variables must be accessed, it must be guaranteed to be used only for calculation logic and there must be noIOOrSleepSuch as cause coordinated process switching operation
  • Do not call any other non-reentrant functions
  • Do not reference memory on stack