Note: The solution is tested on Android 4.2.1, 5.0.2 and 5.1.1.
The value for the system property persist.sys.safemode determines whether the phone should boot into safe mode or in normal mode.
When booted into Android OS, provided root access, the value can be changed as
adb shell su -c 'setprop persist.sys.safemode 1'
adb shell su -c 'echo "1" > /data/property/persist.sys.safemode' #alternative
When booted into a custom recovery, given the data and optionally, system partition are mounted, do
adb shell busybox printf "1" > /data/property/persist.sys.safemode #works if recovery has Busybox. If Android OS has busybox then system/xbin/busybox would work
adb shell echo "1" > /data/property/persist.sys.safemode #alternative
adb shell chmod 600 /data/property/persist.sys.safemode #required; changes the permission of file to rw-------, identical to rest of the files under /data/property
It is to be noted that, if you've never booted into safe mode since last factory reset, the file
persist.sys.safemode wouldn't be found.
Android resets the content of said file at every reboot, so you need not to worry about getting stuck at safe mode. However, for the purpose of fail-safe requirement, change the value to
0 or empty the file (NULL), should you ever get stuck.
In a nutshell, the property that you set is stored in a file, hence it remains persistent when you shutdown the device. You can see your value inside the file from recovery mode, provided that you've not booted into Android again after editing the property. Now, once you begin to boot into Android OS, Android et al reads the file, and based on the content, prepares the safe/ordinary mode for you. After reading the file, it resets the content of the file, so the next time you reboot, it would always be in ordinary mode.
I, in my experiments, noticed that Android would boot into safe mode even if the value is any positive or negative integer or even a decimal value.
I got a good hint from source code of ShutdownThread.java that safe mode requires a system property to be set. However, I reached the final conclusion using a comment by pylerSM and a post from ZiT777.