@@ -1201,6 +1201,111 @@ int64_t js__gettimeofday_us(void) {
12011201 return ((int64_t )tv .tv_sec * 1000000 ) + tv .tv_usec ;
12021202}
12031203
1204+ #if defined(_WIN32 )
1205+ int js_exepath (char * buffer , size_t * size_ptr ) {
1206+ int utf8_len , utf16_buffer_len , utf16_len ;
1207+ WCHAR * utf16_buffer ;
1208+ int err ;
1209+
1210+ if (buffer == NULL || size_ptr == NULL || * size_ptr == 0 ) {
1211+ return -1 ;
1212+ }
1213+
1214+ if (* size_ptr > 32768 ) {
1215+ /* Windows paths can never be longer than this. */
1216+ utf16_buffer_len = 32768 ;
1217+ } else {
1218+ utf16_buffer_len = (int ) * size_ptr ;
1219+ }
1220+
1221+ utf16_buffer = malloc (sizeof (WCHAR ) * utf16_buffer_len );
1222+ if (!utf16_buffer )
1223+ return -1 ;
1224+
1225+ /* Get the path as UTF-16. */
1226+ utf16_len = GetModuleFileNameW (NULL , utf16_buffer , utf16_buffer_len );
1227+ if (utf16_len <= 0 )
1228+ goto error ;
1229+
1230+ /* Convert to UTF-8 */
1231+ utf8_len = WideCharToMultiByte (CP_UTF8 ,
1232+ 0 ,
1233+ utf16_buffer ,
1234+ -1 ,
1235+ buffer ,
1236+ (int ) * size_ptr ,
1237+ NULL ,
1238+ NULL );
1239+ if (utf8_len == 0 )
1240+ goto error ;
1241+
1242+ free (utf16_buffer );
1243+
1244+ /* utf8_len *does* include the terminating null at this point, but the
1245+ * returned size shouldn't. */
1246+ * size_ptr = utf8_len - 1 ;
1247+ return 0 ;
1248+
1249+ error :
1250+ free (utf16_buffer );
1251+ return -1 ;
1252+ }
1253+ #elif defined(__APPLE__ )
1254+ int js_exepath (char * buffer , size_t * size ) {
1255+ /* realpath(exepath) may be > PATH_MAX so double it to be on the safe side. */
1256+ char abspath [PATH_MAX * 2 + 1 ];
1257+ char exepath [PATH_MAX + 1 ];
1258+ uint32_t exepath_size ;
1259+ size_t abspath_size ;
1260+
1261+ if (buffer == NULL || size == NULL || * size == 0 )
1262+ return -1 ;
1263+
1264+ exepath_size = sizeof (exepath );
1265+ if (_NSGetExecutablePath (exepath , & exepath_size ))
1266+ return -1 ;
1267+
1268+ if (realpath (exepath , abspath ) != abspath )
1269+ return -1 ;
1270+
1271+ abspath_size = strlen (abspath );
1272+ if (abspath_size == 0 )
1273+ return -1 ;
1274+
1275+ * size -= 1 ;
1276+ if (* size > abspath_size )
1277+ * size = abspath_size ;
1278+
1279+ memcpy (buffer , abspath , * size );
1280+ buffer [* size ] = '\0' ;
1281+
1282+ return 0 ;
1283+ }
1284+ #elif defined(__linux__ )
1285+ int js_exepath (char * buffer , size_t * size ) {
1286+ ssize_t n ;
1287+
1288+ if (buffer == NULL || size == NULL || * size == 0 )
1289+ return -1 ;
1290+
1291+ n = * size - 1 ;
1292+ if (n > 0 )
1293+ n = readlink ("/proc/self/exe" , buffer , n );
1294+
1295+ if (n == -1 )
1296+ return n ;
1297+
1298+ buffer [n ] = '\0' ;
1299+ * size = n ;
1300+
1301+ return 0 ;
1302+ }
1303+ #else
1304+ int js_exepath (char * buffer , size_t * size_ptr ) {
1305+ return -1 ;
1306+ }
1307+ #endif
1308+
12041309/*--- Cross-platform threading APIs. ----*/
12051310
12061311#if JS_HAVE_THREADS
0 commit comments