1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/platform/wasm/wasm_gate.h"
#include "gate/results.h"
#include "gate/strings.h"

#if defined(GATE_SYS_WASM) && defined(GATE_COMPILER_EMSCRIPTEN)


#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <emscripten/emscripten.h>
#include <emscripten/wasm_worker.h>
#include <emscripten/atomic.h>


static gate_wasm_worker_id_t gate_main_wasm_worker;
static uint32_t gate_main_wasm_worker_id;
static int gate_main_wasm_worker_exit = 0;
static gate_main_func_t global_gate_main = NULL;
static emscripten_wasm_worker_t const RUNTIME_WORKER_ID = 0;
static gate_wasm_worker_id_t const GATE_WASM_WORKER_ID_RUNTIMEMAIN = NULL;

#define GATE_WASM_ENABLE_TRACE 1

#if defined(GATE_WASM_ENABLE_TRACE)
#	define GATE_WASM_TRACE(msg)	gate_wasm_debug_msg(msg)
#	define GATE_WASM_TRACE_STRING(msg) gate_wasm_debug_msg_str(msg)
#else
#	define GATE_WASM_TRACE(msg) do{} while(0)
#	define GATE_WASM_TRACE_STRING(msg) do{} while(0)
#endif

#define GATE_WASM_DEBUG(msg)	gate_wasm_debug_msg(msg)

static gate_bool_t gate_wasm_in_runtime_thread()
{
    return (0 == emscripten_wasm_worker_self_id());
}

static gate_result_t gate_wasm_debug_msg_entrypoint(void* data)
{
    char const* ptr_text = (char const*)data;
    char buffer[4096];
    sprintf(buffer, "console.log('%s')\n", ptr_text);
    emscripten_run_script(buffer);
    return GATE_RESULT_OK;
}

static gate_result_t gate_wasm_debug_msg_entrypoint2(void* data)
{
    char const* ptr_src = (char const*)data;
    gate_size_t len = gate_str_length(ptr_src);
    char buffer[8192] = "console.log('";
    char* ptr_dst = &buffer[13];

    if (len > 4000) len = 4000;

    while (len > 0)
    {
        char c = *ptr_src;
        switch (c)
        {
        case '\\': *ptr_dst = '\\'; ++ptr_dst; c = '\\'; break;
        case '\'': *ptr_dst = '\\'; ++ptr_dst; c = '\''; break;
        case '\"': *ptr_dst = '\\'; ++ptr_dst; c = '\"'; break;
        case '\r': *ptr_dst = '\\'; ++ptr_dst; c = 'r'; break;
        case '\n': *ptr_dst = '\\'; ++ptr_dst; c = 'r'; break;
        case '\t': *ptr_dst = '\\'; ++ptr_dst; c = 't'; break;
        case '\v': *ptr_dst = '\\'; ++ptr_dst; c = 'v'; break;
        case '\f': *ptr_dst = '\\'; ++ptr_dst; c = 'f'; break;
        case '\b': *ptr_dst = '\\'; ++ptr_dst; c = 'b'; break;
        default: break;
        }
        *ptr_dst = c;
        ++ptr_src;
        ++ptr_dst;
        --len;
    }
    *ptr_dst = '\''; ++ptr_dst;
    *ptr_dst = ')'; ++ptr_dst;
    *ptr_dst = ';'; ++ptr_dst;
    *ptr_dst = '\n'; ++ptr_dst;

    free(data);
    emscripten_run_script(buffer);
    return GATE_RESULT_OK;
}

static void gate_wasm_debug_msg(char const* text)
{
    if (gate_wasm_in_runtime_thread())
    {
        gate_wasm_debug_msg_entrypoint((void*)text);
    }
    else
    {
        gate_wasm_worker_post_task(GATE_WASM_WORKER_ID_RUNTIMEMAIN, &gate_wasm_debug_msg_entrypoint, (void*)text);
    }
}
static void gate_wasm_debug_msg_str(gate_string_t const* text)
{
    char* buffer;
    if (gate_string_is_empty(text))
    {
        return;
    }

    buffer = (char*)malloc(text->length + 1);
    gate_mem_copy(buffer, text->str, text->length);
    buffer[text->length] = 0;

    if (gate_wasm_in_runtime_thread())
    {
        gate_wasm_debug_msg_entrypoint2((void*)buffer);
    }
    else
    {
        gate_wasm_worker_post_task(GATE_WASM_WORKER_ID_RUNTIMEMAIN, &gate_wasm_debug_msg_entrypoint2, (void*)buffer);
    }

}

static void gate_wasm_entrypoint_executor_impl(gate_entrypoint_t entry_point, void* param, gate_result_t* ptr_ret)
{
    gate_result_t result = GATE_RESULT_NULLPOINTER;
    if (entry_point)
    {
        result = entry_point(param);
    }
    if (ptr_ret)
    {
        *ptr_ret = result;
    }
}

static void gate_wasm_entrypoint_executor_dispatcher(int func_addr, int func_param, int func_retptr)
{
    gate_entrypoint_t entry_point = (gate_entrypoint_t)func_addr;
    void* ptr_param = (void*)func_param;
    gate_result_t* ptr_ret = (gate_result_t*)func_retptr;

    gate_wasm_entrypoint_executor_impl(entry_point, ptr_param, ptr_ret);
}

typedef struct {
    emscripten_wasm_worker_t	worker_id;
    void* worker_mem;
    emscripten_semaphore_t		completed;
    gate_result_t				exit_code;
} gate_wasm_worker_context_t;

static gate_wasm_worker_context_t registered_wasm_contexts[32];

static emscripten_wasm_worker_t gate_wasm_create_new_worker_context()
{
    static const gate_size_t stack_size = 65536;
    void* worker_mem = malloc(stack_size);
    emscripten_wasm_worker_t new_worker;<--- Shadowed declaration
    unsigned ndx;

    if (worker_mem == NULL)
    {
        return 0;
    }

    for (ndx = 0; ndx != sizeof(registered_wasm_contexts) / sizeof(registered_wasm_contexts[0]); ++ndx)
    {
        gate_wasm_worker_context_t* ptr_ctx = &registered_wasm_contexts[ndx];
        if (!ptr_ctx->worker_id)
        {
            /* empty entry found*/
            emscripten_wasm_worker_t new_worker = emscripten_create_wasm_worker(worker_mem, stack_size);<--- Shadow variable
            if (!new_worker)
            {
                break;
            }
            ptr_ctx->worker_id = new_worker;
            ptr_ctx->worker_mem = worker_mem;
            ptr_ctx->exit_code = 0;
            emscripten_semaphore_init(&ptr_ctx->completed, 0);
            return new_worker;
        }
    }

    /* no free slot, allocation error*/
    if (worker_mem != NULL)
    {
        free(worker_mem);
    }
    return 0;
}

static gate_wasm_worker_context_t* gate_wasm_worker_get_context(emscripten_wasm_worker_t em_worker_id)
{
    unsigned ndx;
    for (ndx = 0; ndx != sizeof(registered_wasm_contexts) / sizeof(registered_wasm_contexts[0]); ++ndx)
    {
        gate_wasm_worker_context_t* ptr_ctx = &registered_wasm_contexts[ndx];
        if (ptr_ctx->worker_id == em_worker_id)
        {
            return ptr_ctx;
        }
    }
    return NULL;
}


static gate_bool_t gate_wasm_destroy_worker_context(emscripten_wasm_worker_t em_worker_id)
{
    gate_wasm_worker_context_t* ptr_ctx = gate_wasm_worker_get_context(em_worker_id);
    if (ptr_ctx)
    {
        free(ptr_ctx->worker_mem);
        ptr_ctx->worker_id = 0;
        ptr_ctx->worker_mem = NULL;
        return true;
    }
    return false;
}

static void gate_wasm_runtimethread_post_worker_task_dispatcher(int target_worker, int entry_addr, int param_addr)
{
    emscripten_wasm_worker_t target_worker_id = (emscripten_wasm_worker_t)target_worker;
    emscripten_wasm_worker_post_function_viii(target_worker_id, &gate_wasm_entrypoint_executor_dispatcher, entry_addr, param_addr, 0);
}

gate_result_t gate_wasm_worker_post_task(gate_wasm_worker_id_t target_worker_id, gate_entrypoint_t entry_point, void* param)
{
    if (gate_wasm_in_runtime_thread())
    {
        /* we are in runtime main thread */
        if (target_worker_id == GATE_WASM_WORKER_ID_RUNTIMEMAIN)
        {
            /* direct execution of task now */
            return entry_point(param);
        }
        else
        {
            /* post task to target worker */
            gate_wasm_runtimethread_post_worker_task_dispatcher((int)target_worker_id, (int)entry_point, (int)param);
            return GATE_RESULT_OK;
        }
    }
    else
    {
        /* we are in a worker -> post task to runtime main thread */
        if (target_worker_id == GATE_WASM_WORKER_ID_RUNTIMEMAIN)
        {
            /* post direct function call to runtime main thread */
            emscripten_wasm_worker_post_function_viii(0, &gate_wasm_entrypoint_executor_dispatcher,
                (int)entry_point, (int)param, 0);
        }
        else
        {
            /* post to runtime main thread to post function to target worker */
            emscripten_wasm_worker_post_function_viii(0, &gate_wasm_runtimethread_post_worker_task_dispatcher,
                (int)target_worker_id, (int)entry_point, (int)param);
        }
        return GATE_RESULT_OK;
    }
}


static void gate_wasm_runtime_execute_dispatcher(int func_addr, int param_addr, int signal_addr)
{
    gate_entrypoint_t func = (gate_entrypoint_t)(intptr_t)func_addr;
    void* ptr_param = (void*)(intptr_t)param_addr;
    emscripten_semaphore_t* ptr_signal = (emscripten_semaphore_t*)(intptr_t)signal_addr;

    if (func)
    {
        func(ptr_param);
    }
    /* signal execution completed */
    emscripten_semaphore_release(ptr_signal, 1);
}

gate_result_t gate_wasm_runtime_execute(gate_entrypoint_t entry_point, void* param)
{
    if (gate_wasm_in_runtime_thread())
    {
        /* we are in browser-runtime-thread -> direct execution*/
        return entry_point(param);
    }
    else
    {
        /* we are in worker -> post to runtime-thread and await completion */
        emscripten_semaphore_t signal = EMSCRIPTEN_SEMAPHORE_T_STATIC_INITIALIZER(0);

        emscripten_wasm_worker_post_function_viii(0, &gate_wasm_runtime_execute_dispatcher,
            (int)(intptr_t)entry_point, (int)(intptr_t)param, (int)(intptr_t)&signal);
        emscripten_semaphore_waitinf_acquire(&signal, 1);
        return GATE_RESULT_OK;
    }
}

gate_wasm_worker_id_t gate_wasm_worker_id()
{
    return (gate_wasm_worker_id_t)emscripten_wasm_worker_self_id();
}


static void gate_wasm_runtimethread_worker_create_dispatcher(int addr_worker, int addr_signal)
{
    gate_wasm_worker_id_t* ptr_worker_id = (gate_wasm_worker_id_t*)addr_worker;
    emscripten_semaphore_t* ptr_signal = (emscripten_semaphore_t*)addr_signal;

    *ptr_worker_id = (gate_wasm_worker_id_t)gate_wasm_create_new_worker_context();
    *ptr_signal = 1;
    GATE_WASM_TRACE("gate_wasm_runtimethread_worker_create_dispatcher()");
    emscripten_semaphore_release(ptr_signal, 1);
}

gate_result_t gate_wasm_worker_create(gate_wasm_worker_id_t* ptr_worker_id)
{
    /*	every new worker MUST be created from browser thread,
        so the browser is parent to every worker
    */
    const gate_bool_t in_browser_runtime_thread = (0 == emscripten_wasm_worker_self_id());
    gate_wasm_worker_id_t new_worker_id = NULL;

    if (in_browser_runtime_thread)
    {
        /* we are in runtime main thread */
        new_worker_id = (gate_wasm_worker_id_t)gate_wasm_create_new_worker_context();
    }
    else
    {
        /* worker thread -> switch to parent(==browser-runtime) thread  */
        emscripten_semaphore_t signal = EMSCRIPTEN_SEMAPHORE_T_STATIC_INITIALIZER(0);

        emscripten_wasm_worker_post_function_vii(0, &gate_wasm_runtimethread_worker_create_dispatcher,
            (int)&new_worker_id, (int)&signal);
        emscripten_semaphore_waitinf_acquire(&signal, 1);
    }

    if (new_worker_id == NULL)
    {
        return GATE_RESULT_OUTOFRESOURCES;
    }

    if (ptr_worker_id)
    {
        *ptr_worker_id = new_worker_id;
    }
    return GATE_RESULT_OK;
}

gate_result_t gate_wasm_worker_completed(gate_wasm_worker_id_t worker_id, gate_result_t exit_code)
{
    gate_wasm_worker_context_t* ptr_ctx = gate_wasm_worker_get_context((int)(intptr_t)worker_id);
    if (NULL == ptr_ctx)
    {
        return GATE_RESULT_NOTAVAILABLE;
    }
    ptr_ctx->exit_code = exit_code;
    emscripten_semaphore_release(&ptr_ctx->completed, 32767);
    return GATE_RESULT_OK;
}

gate_result_t gate_wasm_worker_join(gate_wasm_worker_id_t worker_id, gate_result_t* ptr_exit_code)
{
    gate_wasm_worker_context_t* ptr_ctx = gate_wasm_worker_get_context((int)(intptr_t)worker_id);
    if (NULL == ptr_ctx)
    {
        return GATE_RESULT_NOTAVAILABLE;
    }
    emscripten_semaphore_waitinf_acquire(&ptr_ctx->completed, 1);
    if (ptr_exit_code)
    {
        *ptr_exit_code = ptr_ctx->exit_code;
    }
    return GATE_RESULT_OK;
}


gate_result_t gate_wasm_worker_destroy(gate_wasm_worker_id_t worker_id)
{
    int em_worker_id = (int)(intptr_t)worker_id;
    if (em_worker_id == 0)
    {
        return GATE_RESULT_INVALIDARG;
    }
    if (!gate_wasm_destroy_worker_context(em_worker_id))
    {
        return GATE_RESULT_FAILED;
    }
    return GATE_RESULT_OK;
}


static gate_result_t gate_wasm_main_executor_disatcher(void* param)
{
    char const* program_name = NULL;
    char const* const* args = NULL;
    gate_size_t args_count = 0;
    gate_uintptr_t app_handle = (gate_uintptr_t)gate_main_wasm_worker;
    GATE_WASM_TRACE("ENTER gate_wasm_main_executor_disatcher()");

    gate_main_wasm_worker_id = emscripten_wasm_worker_self_id();

    if (0 == gate_main_wasm_worker_id)
    {
        GATE_WASM_DEBUG("ERROR: 0 cannot be the ID of a worker");
        return GATE_RESULT_UNKNOWNERROR;
    }

    if (global_gate_main)
    {
        GATE_WASM_TRACE("Executing: gate_main() function");
        gate_main_wasm_worker_exit = global_gate_main(program_name, args, args_count, app_handle);
        GATE_WASM_TRACE("Completed: gate_main() function");
    }
    return GATE_RESULT_OK;
}

void gate_wasm_register_gate_main(gate_main_func_t func)
{
    GATE_WASM_TRACE("ENTER gate_wasm_register_gate_main()");
    global_gate_main = func;
}

gate_result_t gate_wasm_main_init()
{
    GATE_WASM_TRACE("ENTER gate_wasm_main_init()");
    return GATE_RESULT_OK;
}

int gate_wasm_start_main()
{
    gate_result_t result;

    GATE_WASM_TRACE("ENTER gate_wasm_start_main()");

    if (global_gate_main)
    {
        result = gate_wasm_worker_create(&gate_main_wasm_worker);
        if (GATE_FAILED(result))
        {
            GATE_WASM_DEBUG("Failed to allocate WASM WORKER");
            return 1;
        }
        gate_wasm_worker_post_task(gate_main_wasm_worker, &gate_wasm_main_executor_disatcher, NULL);
    }
    return 0;
}


gate_result_t gate_wasm_thread_create(gate_entrypoint_t entry_point, void* param, gate_wasm_thread_id_t* ptr_thread_id)
{
    gate_result_t result;
    gate_wasm_worker_id_t worker_id;

    GATE_WASM_TRACE("ENTER gate_wasm_thread_create()");

    do
    {
        result = gate_wasm_worker_create(&worker_id);
        GATE_BREAK_IF_FAILED(result);

        if (ptr_thread_id)
        {
            *ptr_thread_id = (gate_wasm_thread_id_t)worker_id;
        }
        result = gate_wasm_worker_post_task(worker_id, entry_point, param);
    } while (0);

    return result;
}

void gate_wasm_thread_sleep(gate_uint32_t timeout_ms)
{
    emscripten_wasm_worker_sleep((gate_int64_t)timeout_ms * (gate_int64_t)1000000);
}

int gate_wasm_atomic_get(int* ptr_int)
{
    return (int)emscripten_atomic_load_u32(ptr_int);
}
int gate_wasm_atomic_set(int* ptr_int, int new_int)
{
    return (int)emscripten_atomic_exchange_u32(ptr_int, (uint32_t)new_int);
}
int gate_wasm_atomic_add(int* ptr_int, int add_int)
{
    return (int)emscripten_atomic_add_u32(ptr_int, (uint32_t)add_int);
}
int gate_wasm_atomic_exchange(int* ptr_int, int compare_int, int new_int)
{
    return (int)emscripten_atomic_cas_u32(ptr_int, (uint32_t)compare_int, (uint32_t)new_int);
}



static emscripten_lock_t wasm_console_read_main_lock = EMSCRIPTEN_LOCK_T_STATIC_INITIALIZER;
static emscripten_semaphore_t wasm_console_read_worker_wait_lock = EMSCRIPTEN_SEMAPHORE_T_STATIC_INITIALIZER(0);

static unsigned char wasm_console_read_buffer[64];
static unsigned wasm_console_read_buffer_used = 0;

static gate_bool_t wasm_read_buffer_push_char(unsigned char received_char)
{
    gate_bool_t ret = false;
    if (gate_wasm_in_runtime_thread())
    {
        // TODO: use lock_try() and move code to background-worker in locked-case
        emscripten_lock_busyspin_waitinf_acquire(&wasm_console_read_main_lock);
    }
    else
    {
        emscripten_lock_waitinf_acquire(&wasm_console_read_main_lock);
    }

    if (wasm_console_read_buffer_used < sizeof(wasm_console_read_buffer))
    {
        wasm_console_read_buffer[wasm_console_read_buffer_used] = received_char;
        ++wasm_console_read_buffer_used;
        ret = true;
    }
    emscripten_lock_release(&wasm_console_read_main_lock);
    return ret;
}
static int wasm_read_buffer_pop_char()
{
    int ret = -1;
    unsigned ndx;

    emscripten_lock_waitinf_acquire(&wasm_console_read_main_lock);
    if (wasm_console_read_buffer_used > 0)
    {
        ret = wasm_console_read_buffer[0];
        for (ndx = 1; ndx < wasm_console_read_buffer_used; ++ndx)
        {
            wasm_console_read_buffer[ndx - 1] = wasm_console_read_buffer[ndx];
        }
        --wasm_console_read_buffer_used;
    }
    emscripten_lock_release(&wasm_console_read_main_lock);
    return ret;
}

static void wasm_read_buffer_receive_char(char received_char)
{
    if (wasm_read_buffer_push_char(received_char))
    {
        /* wake up one sleeping worker */
        emscripten_semaphore_release(&wasm_console_read_worker_wait_lock, 1);
    }
}

EMSCRIPTEN_KEEPALIVE int gate_wasm_html_console_char_received_notification(int received_char)
{
    GATE_WASM_TRACE("gate_wasm_html_console_char_received_notification");
    wasm_read_buffer_receive_char((char)received_char);
    return 1;
}

static int console_initialized = 0;

static gate_bool_t is_console_initialized()
{
    return gate_wasm_atomic_get(&console_initialized) != 0;
}

static gate_result_t init_console_impl(gate_dataptr_t arg)
{
    if (0 == gate_wasm_atomic_set(&console_initialized, 1))
    {
        EM_ASM({
            //console.log("Initializing GATE WASM HTML console");
            const console_id = "gate_wasm_html_console";
            var element = document.getElementById(console_id);
            if (element == null) {
                element = document.createElement("pre");
                element.id = console_id;
                element.tabIndex = 0;
                document.body.appendChild(element);
            }
            element.send_input_char = function(charCode) {
                Module.ccall("gate_wasm_html_console_char_received_notification", "number",["number"],[charCode]);
            };
            element.addEventListener("keypress", function(event) {
                //console.log("Key pressed:", event.key, event.code);
                var k = event.key;
                if (k == "Enter") { k = "\n"; }
                else if (k == "Backspace") { k = String.fromCharCode(9); }
                element.innerText += k;
                input_char = k.charCodeAt(0);
                element.send_input_char(input_char);
            });
            element.focus();
            });
    }
    return GATE_RESULT_OK;
}

void gate_wasm_console_init()
{
    gate_wasm_runtime_execute(&init_console_impl, NULL);
}

int gate_wasm_console_read(gate_uint32_t timeout_ms)
{
    int value;<--- Unused variable: value
    int cnt;
    if (timeout_ms == 0xffffffff)
    {
        cnt = emscripten_semaphore_waitinf_acquire(&wasm_console_read_worker_wait_lock, 1);
    }
    else
    {
        cnt = emscripten_semaphore_wait_acquire(&wasm_console_read_worker_wait_lock, 1, (gate_int64_t)timeout_ms * 1000000);
    }

    if (cnt < 0)
    {
        GATE_WASM_DEBUG("Failed to wait for console-read semaphore");
        return -1;
    }
    return wasm_read_buffer_pop_char();
}

static gate_result_t gate_wasm_console_write_impl(void* ptr)
{
    int chr = (unsigned char)(int)ptr;
    EM_ASM_ARGS({
        //console.log("Write character to console");
        const console_id = "gate_wasm_html_console";
        var element = document.getElementById(console_id);
        element.innerText += String.fromCharCode($0);
        element.focus();
        }, chr);
    return GATE_RESULT_OK;
}

void gate_wasm_console_write(char chr)
{
    void* chr_param = (void*)(int)(unsigned char)chr;
    if (gate_wasm_in_runtime_thread())
    {
        gate_wasm_console_write_impl((void*)(int)chr_param);
    }
    else
    {
        gate_wasm_runtime_execute(&gate_wasm_console_write_impl, chr_param);
    }
}



gate_intptr_t gate_wasm_read(int fd, void* buf, gate_size_t nbytes)
{
    gate_uint32_t next_timeout = 0xffffffff;
    int chr = 0;
    char* ptr_target = (char*)buf;
    gate_size_t received = 0;

    GATE_WASM_TRACE("ENTER gate_wasm_read()");

    if ((fd == 1) || (fd == 2))
    {
        /* cannot read from STDOUT or STDERR */
        return -1;
    }
    else if (fd == 0)
    {
        while (received < nbytes)
        {
            chr = gate_wasm_console_read(next_timeout);
            if (chr < 0)
            {
                /* receive/wait error */
                if (received == 0)
                {
                    return -1;
                }
            }
            else
            {
                /* char received*/
                *ptr_target = (char)(unsigned char)chr;
                ++ptr_target;
                ++received;
            }
            next_timeout = 0;
        }
        return (gate_intptr_t)received;
    }
    else
    {
        return read(fd, buf, nbytes);
    }
}


struct gate_wasm_write_dispatcher_params
{
    int fd;
    void const* buf;
    gate_size_t nbytes;
    gate_intptr_t result;
};

static gate_result_t gate_wasm_write_dispatcher(void* param)
{
    struct gate_wasm_write_dispatcher_params* params = (struct gate_wasm_write_dispatcher_params*)param;
    params->result = write(params->fd, params->buf, params->nbytes);
    return GATE_RESULT_OK;
}

gate_intptr_t gate_wasm_write(int fd, const void* buf, gate_size_t nbytes)
{
    GATE_WASM_TRACE("ENTER gate_wasm_write()");

    if (fd == 0)
    {
        /* cannot write to STDIN */
        return -1;
    }
    if ((fd == 1) && is_console_initialized())
    {
        char const* ptr = (char const*)buf;
        unsigned ndx;
        for (ndx = 0; ndx != nbytes; ++ndx, ++ptr)
        {
            gate_wasm_console_write(*ptr);
        }
        return (gate_intptr_t)nbytes;
    }

    if (gate_wasm_in_runtime_thread())
    {
        return write(fd, buf, nbytes);
    }
    else
    {
        gate_result_t result;
        struct gate_wasm_write_dispatcher_params params = { fd, buf, nbytes, 0 };
        result = gate_wasm_runtime_execute(&gate_wasm_write_dispatcher, &params);
        if (GATE_FAILED(result))
        {
            return -1;
        }
        return params.result;
    }
}

gate_result_t gate_wasm_seek(int fd, gate_int64_t position, int origin, gate_int64_t* final_position)
{
    return GATE_RESULT_NOTIMPLEMENTED;
}
gate_result_t gate_wasm_close(int fd)
{
    GATE_WASM_TRACE("ENTER gate_wasm_close()");
    close(fd);
    return GATE_RESULT_OK;
}


void gate_wasm_exit(int exit_code)
{
    GATE_WASM_TRACE("ENTER gate_wasm_exit()");
    emscripten_force_exit(exit_code);
}


static emscripten_semaphore_t wasm_global_lock_sem = EMSCRIPTEN_SEMAPHORE_T_STATIC_INITIALIZER(1);

gate_result_t gate_wasm_global_lock()
{
    int cnt = emscripten_semaphore_waitinf_acquire(&wasm_global_lock_sem, 1);
    return (cnt < 0) ? GATE_RESULT_FAILED : GATE_RESULT_OK;
}
gate_result_t gate_wasm_global_unlock()
{
    emscripten_semaphore_release(&wasm_global_lock_sem, 1);
    return GATE_RESULT_OK;
}

static int global_last_error = 0;

gate_int32_t gate_wasm_get_last_error()
{
    //TODO
    return gate_wasm_atomic_get(&global_last_error);
}
gate_result_t gate_wasm_set_last_error(gate_int32_t platform_error_code)
{
    //TODO
    gate_wasm_atomic_set(&global_last_error, platform_error_code);
    return GATE_RESULT_OK;
}
gate_result_t gate_wasm_print_error(gate_int32_t platform_error_code, char* buffer, gate_size_t buffer_len)
{
    //TODO
    return GATE_RESULT_FAILED;
}

gate_result_t gate_wasm_sem_create(gate_uint32_t volatile* sem, unsigned num)
{
    emscripten_semaphore_t* s = (emscripten_semaphore_t*)sem;

    if (!s || (num == 0))
    {
        return GATE_RESULT_INVALIDARG;
    }
    emscripten_semaphore_init(s, (int)num);
    return GATE_RESULT_OK;
}
gate_result_t gate_wasm_sem_acquire(gate_uint32_t volatile* sem, gate_uint32_t const* timeout_ms)
{
    emscripten_semaphore_t* s = (emscripten_semaphore_t*)sem;
    int result;
    if (!s)
    {
        return GATE_RESULT_INVALIDARG;
    }

    if (gate_wasm_in_runtime_thread())
    {
        if (!timeout_ms)
        {
            while (-1 == emscripten_semaphore_try_acquire(sem, 1))
            {
                // wait until try_acquire succeeds
            }
            result = 0;
        }
        else
        {
            /* TODO: correct implementation */
            result = emscripten_semaphore_wait_acquire(s, 1, ((int64_t)*timeout_ms * 1000000LL));
        }
    }
    else
    {
        if (!timeout_ms)
        {
            result = emscripten_semaphore_waitinf_acquire(s, 1);
        }
        else
        {
            result = emscripten_semaphore_wait_acquire(s, 1, ((int64_t)*timeout_ms * 1000000LL));
        }
    }
    return (result == -1) ? GATE_RESULT_TIMEOUT : GATE_RESULT_OK;
}
gate_result_t gate_wasm_sem_release(gate_uint32_t volatile* sem)
{
    emscripten_semaphore_t* s = (emscripten_semaphore_t*)sem;
    if (!s)
    {
        return GATE_RESULT_INVALIDARG;
    }
    emscripten_semaphore_release(s, 1);
    return GATE_RESULT_OK;
}
gate_result_t gate_wasm_sem_destroy(gate_uint32_t volatile* sem)
{
    if (!sem)
    {
        return GATE_RESULT_INVALIDARG;
    }
    return GATE_RESULT_OK;
}


/* WASM HTML CANVAS: */

static emscripten_lock_t wasm_canvas_event_lock = EMSCRIPTEN_LOCK_T_STATIC_INITIALIZER;
static emscripten_semaphore_t wasm_canvas_event_wait_signal = EMSCRIPTEN_SEMAPHORE_T_STATIC_INITIALIZER(0);

typedef struct
{
    gate_uint16_t	id;
    gate_uint32_t	data;
} wasm_canvas_event_t;

static wasm_canvas_event_t wasm_canvas_event_buffer[64];
static unsigned wasm_canvas_event_buffer_used = 0;

static gate_bool_t wasm_canvas_event_push(gate_uint16_t id, gate_uint32_t data)
{
    gate_bool_t ret = false;
    if (gate_wasm_in_runtime_thread())
    {
        emscripten_lock_busyspin_waitinf_acquire(&wasm_canvas_event_lock);
    }
    else
    {
        emscripten_lock_waitinf_acquire(&wasm_canvas_event_lock);
    }

    if (wasm_canvas_event_buffer_used < sizeof(wasm_canvas_event_buffer) / sizeof(wasm_canvas_event_buffer[0]))
    {
        wasm_canvas_event_buffer[wasm_canvas_event_buffer_used].id = id;
        wasm_canvas_event_buffer[wasm_canvas_event_buffer_used].data = data;
        ++wasm_canvas_event_buffer_used;
        ret = true;
    }
    emscripten_lock_release(&wasm_canvas_event_lock);

    if (ret)
    {
        emscripten_semaphore_release(&wasm_canvas_event_wait_signal, 1);
    }
    return ret;
}
static gate_bool_t wasm_canvas_event_pop(wasm_canvas_event_t* ptr_event)
{
    gate_bool_t ret = false;
    unsigned ndx;

    emscripten_lock_waitinf_acquire(&wasm_canvas_event_lock);
    if (wasm_canvas_event_buffer_used > 0)
    {
        *ptr_event = wasm_canvas_event_buffer[0];
        ret = true;
        for (ndx = 1; ndx < wasm_canvas_event_buffer_used; ++ndx)
        {
            wasm_canvas_event_buffer[ndx - 1] = wasm_canvas_event_buffer[ndx];
        }
        --wasm_canvas_event_buffer_used;
    }
    emscripten_lock_release(&wasm_canvas_event_lock);
    return ret;
}



static gate_uint16_t encode_mouseevent_button_param(int button)
{
    switch (button)
    {
    case 0:	return GATE_WASM_CANVAS_EVENT_FLAG_LEFT; break;
    case 1: return GATE_WASM_CANVAS_EVENT_FLAG_MIDDLE; break;
    case 2: return GATE_WASM_CANVAS_EVENT_FLAG_RIGHT; break;
    default: return 0;
    }
}

static gate_uint32_t encode_mouseevent_coords(int x, int y)
{
    return ((gate_uint32_t)x << 16) | ((gate_uint32_t)y & 0xffff);
}

EMSCRIPTEN_KEEPALIVE int gate_wasm_html_canvas_event_mousedown_notification(int button, int x, int y)
{
    return wasm_canvas_event_push(
        GATE_WASM_CANVAS_EVENT_ID_POINTER_DOWN | encode_mouseevent_button_param(button),
        encode_mouseevent_coords(x, y)
    );
}
EMSCRIPTEN_KEEPALIVE int gate_wasm_html_canvas_event_mouseup_notification(int button, int x, int y)
{
    return wasm_canvas_event_push(
        GATE_WASM_CANVAS_EVENT_ID_POINTER_UP | encode_mouseevent_button_param(button),
        encode_mouseevent_coords(x, y)
    );
}
EMSCRIPTEN_KEEPALIVE int gate_wasm_html_canvas_event_mousemove_notification(int button, int x, int y)
{
    return wasm_canvas_event_push(
        GATE_WASM_CANVAS_EVENT_ID_POINTER_MOVE | encode_mouseevent_button_param(button),
        encode_mouseevent_coords(x, y)
    );
}

static gate_uint16_t encode_special_keys(int ctrl, int shift, int alt)
{
    gate_uint16_t flags = 0;
    if (ctrl)	flags |= GATE_WASM_CANVAS_EVENT_FLAG_CTRL;
    if (shift)	flags |= GATE_WASM_CANVAS_EVENT_FLAG_SHIFT;
    if (alt)		flags |= GATE_WASM_CANVAS_EVENT_FLAG_ALT;
    return flags;
}

EMSCRIPTEN_KEEPALIVE int gate_wasm_html_canvas_event_keydown_notification(int keycode, int ctrl, int shift, int alt)
{
    return wasm_canvas_event_push(
        GATE_WASM_CANVAS_EVENT_ID_KEY_DOWN | encode_special_keys(ctrl, shift, alt),
        (gate_uint32_t)keycode
    );
}

EMSCRIPTEN_KEEPALIVE int gate_wasm_html_canvas_event_keyup_notification(int keycode, int ctrl, int shift, int alt)
{
    return wasm_canvas_event_push(
        GATE_WASM_CANVAS_EVENT_ID_KEY_UP | encode_special_keys(ctrl, shift, alt),
        (gate_uint32_t)keycode
    );
}


static gate_result_t gate_wasm_canvas_init_impl(void* param)
{
    const gate_uint32_t nparam = (gate_uint32_t)param;
    const gate_uint16_t width = (gate_uint16_t)((nparam >> 16) & 0xffff);
    const gate_uint16_t height = (gate_uint16_t)(nparam & 0xffff);
    EM_ASM_ARGS({
        //console.log("Initializing GATE WASM CANVAS console");
        window.map_key_event_to_char_code = function(evt) {
            if (event.key.length == 1) return event.key.charCodeAt(0);
            if (event.key == "Escape") return 0x1b;
            if (event.key == "Enter") return 13;
            if (event.key == "Tab") return 9;
            if (event.key == "Backspace") return 8;
            if (event.key == "ArrowDown") return 0;
            if (event.key == "ArrowUp") return 0;
            if (event.key == "ArrowLeft") return 0;
            if (event.key == "ArrowRight") return 0;
            return evt.keyCode;
        };
        const canvas_id = "gate_wasm_html_canvas";
        var element = document.getElementById(canvas_id);
        if (element == null) {
            element = document.createElement("canvas");
            element.id = canvas_id;
            element.tabIndex = 0;
            document.body.appendChild(element);
        }
        element.width = $0;
        element.height = $1;
        element.send_mouse_down = function(btn, x, y) {
            Module.ccall("gate_wasm_html_canvas_event_mousedown_notification", "number",
                ["number","number","number"],[btn, x, y]);
        };
        element.send_mouse_up = function(btn, x, y) {
            Module.ccall("gate_wasm_html_canvas_event_mouseup_notification", "number",
                ["number","number","number"],[btn, x, y]);
        };
        element.send_mouse_move = function(btn, x, y) {
            Module.ccall("gate_wasm_html_canvas_event_mousemove_notification", "number",
                ["number","number","number"],[btn, x, y]);
        };
        element.send_key_down = function(keycode, ctrl, shift, alt) {
            Module.ccall("gate_wasm_html_canvas_event_keydown_notification", "number",
                ["number","number","number","number"],[keycode, ctrl, shift, alt]);
        };
        element.send_key_up = function(keycode, ctrl, shift, alt) {
            Module.ccall("gate_wasm_html_canvas_event_keyup_notification", "number",
                ["number","number","number","number"],[keycode, ctrl, shift, alt]);
        };

        element.addEventListener("mousedown", function(event) {
            //console.log("Mouse down:", event.offsetX, event.offsetY);
            element.send_mouse_down(event.button, event.offsetX, event.offsetY);
        });
        element.addEventListener("mouseup", function(event) {
            //console.log("Mouse up:", event.offsetX, event.offsetY);
            element.send_mouse_up(event.button, event.offsetX, event.offsetY);
        });
        //element.addEventListener("mousemove", function(event) { 
        //	console.log("Mouse move:", event.offsetX, event.offsetY);
        //	element.send_mouse_move(event.button, event.offsetX, event.offsetY);
        //});
        element.addEventListener("keydown", function(event) {
            //console.log("Key down:", event.key, event.code);
            element.send_key_down(window.map_key_event_to_char_code(event), event.ctrlKey, event.shiftKey, event.altKey);
        });
        element.addEventListener("keyup", function(event) {
            //console.log("Key up:", event.key, event.code);
            element.send_key_up(window.map_key_event_to_char_code(event), event.ctrlKey, event.shiftKey, event.altKey);
        });
        element.focus();
        }, (int)width, (int)height);
    return GATE_RESULT_OK;
}

void gate_wasm_canvas_init(gate_uint16_t width, gate_uint16_t height)
{
    gate_uint32_t nparam = (((gate_uint32_t)width) << 16) | ((gate_uint32_t)height);
    gate_wasm_runtime_execute(&gate_wasm_canvas_init_impl, (void*)nparam);
}

typedef struct {
    gate_uint16_t x;
    gate_uint16_t y;
    char const* html5_image;
} gate_wasm_canvas_put_image_param_t;

static gate_result_t gate_wasm_canvas_put_image_impl(void* param)
{
    gate_wasm_canvas_put_image_param_t* p = (gate_wasm_canvas_put_image_param_t*)param;
    EM_ASM_ARGS({
        const x = $0;
        const y = $1;
        const content = $2;
        //console.log("ENTER gate_wasm_canvas_put_image()");
        var img = new Image();
        img.onload = function() {
            const canvas_id = "gate_wasm_html_canvas";
            var canvas = document.getElementById(canvas_id);
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, x, y, img.width, img.height);
            canvas.focus();
        };
        img.src = UTF8ToString(content);
        }, (int)p->x, (int)p->y, p->html5_image);
    return GATE_RESULT_OK;
}

gate_result_t gate_wasm_canvas_put_image(gate_uint16_t x, gate_uint16_t y, char const* html5_image)
{
    gate_wasm_canvas_put_image_param_t param;
    param.x = x;
    param.y = y;
    param.html5_image = html5_image;

    if (gate_wasm_in_runtime_thread())
    {
        return gate_wasm_canvas_put_image_impl(&param);
    }
    else
    {
        return gate_wasm_runtime_execute(&gate_wasm_canvas_put_image_impl, &param);
    }
}

gate_bool_t gate_wasm_canvas_await_event(gate_uint32_t timeout_ms, gate_uint16_t* event_id, gate_uint32_t* event_data)
{
    int value;<--- Unused variable: value
    int cnt;
    wasm_canvas_event_t evt = GATE_INIT_EMPTY;

    if (timeout_ms == 0xffffffff)
    {
        cnt = emscripten_semaphore_waitinf_acquire(&wasm_canvas_event_wait_signal, 1);
    }
    else
    {
        cnt = emscripten_semaphore_wait_acquire(&wasm_canvas_event_wait_signal, 1, (gate_int64_t)timeout_ms * 1000000);
    }

    if (cnt >= 0)
    {
        GATE_WASM_TRACE("WASM canvas event received");
        if (wasm_canvas_event_pop(&evt))
        {
            if (event_id) *event_id = evt.id;
            if (event_data) *event_data = evt.data;
            return true;
        }
    }
    return false;
}


gate_bool_t gate_wasm_fs_mount(enum gate_wasm_fs_type type, char const* path)
{
    int ret = 0;
    switch (type)
    {
    case wasm_fs_type_memfs:
        ret = EM_ASM_INT({
            try {
                FS.mount(MEMFS, {}, $0);
                return 1;
            }
 catch (error) {}
return 0;
            }, path);
        break;
    case wasm_fs_type_nodefs:
        ret = EM_ASM_INT({
            try {
                FS.mount(NODEFS, {}, $0);
                return 1;
            }
 catch (error) {}
return 0;
            }, path);
        break;
    case wasm_fs_type_idbfs:
        ret = EM_ASM_INT({
            try {
                FS.mount(IDBFS, {}, $0);
                return 1;
            }
 catch (error) {}
return 0;
            }, path);
        break;
    case wasm_fs_type_workerfs:
        ret = EM_ASM_INT({
            try {
                FS.mount(WORKERFS, {}, $0);
                return 1;
            }
 catch (error) {}
return 0;
            }, path);
        break;
    }
    return ret != 0;
}
gate_bool_t gate_wasm_fs_unmount(char const* path)
{
    int ret = 0;
    ret = EM_ASM_INT({
        try {
            FS.unmount($0);
            return 1;
        }
 catch (error) {}
return 0;
        }, path);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_syncfs(gate_bool_t populate)
{
    int ret = 0;
    if (populate)
    {
        ret = EM_ASM_INT({
            try {
                FS.syncfs(true, function(err) {});
                return 1;
            }
 catch (error) {}
return 0;
            });
    }
    else
    {
        ret = EM_ASM_INT({
            try {
                FS.syncfs(false, function(err) {});
                return 1;
            }
 catch (error) {}
return 0;
            });
    }
    return ret != 0;
}

gate_bool_t gate_wasm_fs_mkdir(char const* path, int mode)
{
    int ret = 0;
    ret = EM_ASM_INT({
        try {
            FS.mkdir($0, $1);
            return 1;
        }
 catch (error) {}
return 0;
        }, path, mode);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_symlink(char const* oldpath, char const* newpath)
{
    int ret = 0;<--- 'ret' is assigned value '0' here.
    EM_ASM_ARGS({
        try {
            FS.symlink($0, $1);
            return 1;
        }
 catch (error) {}
return 0;
        }, oldpath, newpath);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_rename(char const* oldpath, char const* newpath)
{
    int ret = 0;<--- 'ret' is assigned value '0' here.
    EM_ASM_ARGS({
        try {
            FS.rename($0, $1);
            return 1;
        }
 catch (error) {}
return 0;
        }, oldpath, newpath);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_rmdir(char const* path)
{
    int ret = 0;
    EM_ASM_ARGS({
        try {
            FS.rmdir($0);
            return 1;
        }
 catch (error) {}
return 0;
        }, path);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_unlink(char const* path)
{
    int ret = 0;<--- 'ret' is assigned value '0' here.
    EM_ASM_ARGS({
        try {
            FS.unlink($0);
            return 1;
        }
 catch (error) {}
return 0;
        }, path);
    return ret != 0;
}

gate_size_t wasm_fs_jsstrptr_to_buffer(int int_str_ptr, char real_path[], gate_size_t real_path_capacity)
{
    char* ptr_str = (char*)int_str_ptr;
    gate_size_t str_len = gate_str_length(ptr_str);
    gate_size_t ret = gate_str_print_text(real_path, real_path_capacity, ptr_str, str_len);
    free(ptr_str);
    return ret;
}

#define RETURN_JS_STRING(strvar) \
	var lengthBytes = lengthBytesUTF8(strvar) + 1; \
	var stringOnWasmHeap = _malloc(lengthBytes); \
	stringToUTF8(strvar, stringOnWasmHeap, lengthBytes); \
	return stringOnWasmHeap


gate_size_t wasm_fs_readlink(char const* link, char real_path[], gate_size_t real_path_capacity)
{
    int int_str_ptr = EM_ASM_INT({
        try {
            var str = FS.readlink($0);
            RETURN_JS_STRING(str);
        }
 catch (error) {}
return 0;
        }, link);
    if (int_str_ptr == 0)
    {
        return 0;
    }
    return wasm_fs_jsstrptr_to_buffer(int_str_ptr, real_path, real_path_capacity);
}

gate_bool_t wasm_fs_stat(char const* path, gate_wasm_fs_stat_t* ptr_stat)
{
    gate_size_t used;
    char buffer[2048];
    int int_str_ptr = EM_ASM_INT({
        try {
            str = JSON.stringify(FS.stat($0));
            RETURN_JS_STRING(str);
        }
 catch (error) {}
return 0;
        }, path);

    if (int_str_ptr)
    {
        return false;
    }

    used = wasm_fs_jsstrptr_to_buffer(int_str_ptr, buffer, sizeof(buffer));
    /*
    {
        dev: 1,
        ino: 13,
        mode: 33206,
        nlink: 1,
        uid: 0,
        gid: 0,
        rdev: 0,
        size: 6,
        atime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST),
        mtime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST),
        ctime: Mon Nov 25 2013 00:37:27 GMT-0800 (PST),
        blksize: 4096,
        blocks: 1
    }
    */
    gate_mem_clear(ptr_stat, sizeof(gate_wasm_fs_stat_t));
    /* TODO */
    return true;
}

gate_bool_t gate_wasm_fs_lstat(char const path[], gate_wasm_fs_stat_t* ptr_stat)
{
    gate_size_t used;
    char buffer[2048];
    int int_str_ptr = EM_ASM_INT({
        try {
            str = JSON.stringify(FS.lstat($0));
            RETURN_JS_STRING(str);
        }
 catch (error) {}
return 0;
        }, path);

    if (int_str_ptr)
    {
        return false;
    }

    used = wasm_fs_jsstrptr_to_buffer(int_str_ptr, buffer, sizeof(buffer));
    gate_mem_clear(ptr_stat, sizeof(gate_wasm_fs_stat_t));
    return true;
}

gate_bool_t gate_wasm_fs_chmod(char const path[], unsigned mode)
{
    int ret = EM_ASM_INT({
        try {
            FS.chmod($0, $1);
            return 1;
        }
 catch (error) {}
return 0;
        }, path, mode);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_chown(char const path[], int uid, int gid)
{
    int ret = EM_ASM_INT({
        try {
            FS.chown($0, $1, $2);
            return 1;
        }
 catch (error) {}
return 0;
        }, path, uid, gid);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_trunc(char const path[], gate_int64_t len)
{
    int ret = EM_ASM_INT({
        try {
            FS.truncate($0, $1);
            return 1;
        }
 catch (error) {}
return 0;
        }, path, len);
    return ret != 0;
}

gate_bool_t gate_wasm_fs_utime(char const path[], gate_int64_t atime, gate_int64_t mtime)
{
    int ret = EM_ASM_INT({
        try {
            FS.utime($0, $1, $2);
            return 1;
        }
 catch (error) {}
return 0;
        }, path, atime, mtime);
    return ret != 0;
}

gate_enumint_t gate_wasm_fs_filetype(int mode)
{
    int ret = EM_ASM_INT({
        try {
            var tp = 0;
            if (FS.isFile($0)) tp |= GATE_WASM_FILETYPE_FILE;
            if (FS.isDir($0)) tp |= GATE_WASM_FILETYPE_DIR;
            if (FS.isChrdev($0) || FS.isBlkdev($0)) tp |= GATE_WASM_FILETYPE_DEV;
            if (FS.isLink($0)) tp |= GATE_WASM_FILETYPE_LINK;
            return tp;
        }
 catch (error) {}
return 0;
        }, mode);
    return (gate_enumint_t)ret;
}

gate_size_t gate_wasm_fs_cwd(char path[], gate_size_t path_capacity)
{
    int int_str_ptr = EM_ASM_INT({
        try {
            var str = FS.cwd();
            RETURN_JS_STRING(str);
        }
 catch (error) {}
return 0;
        });
    if (int_str_ptr == 0)
    {
        return 0;
    }
    return wasm_fs_jsstrptr_to_buffer(int_str_ptr, path, path_capacity);
}

gate_bool_t gate_wasm_fs_chdir(char const path[])
{
    int ret = EM_ASM_INT({
        try {
            FS.chdir($0);
            return 1;
        }
 catch (error) {}
return 0;
        }, path);
    return ret != 0;
}

gate_size_t gate_wasm_fs_readdir(char const path[], gate_string_t names[], gate_size_t names_capacity)
{
    /* TODO */
    return 0;
}


void gate_wasm_js_encode_string(gate_strbuilder_t* builder, gate_string_t const* str)
{
    char const* ptr = gate_string_ptr(str, 0);
    gate_size_t len = gate_string_length(str);
    while (len > 0)
    {
        const char c = *ptr;
        switch (c)
        {
        case '\\': gate_strbuilder_append_chars(builder, 2, '\\'); break;
        case '\'': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, '\''); break;
        case '\"': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, '\"'); break;
        case '\r': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, 'r'); break;
        case '\n': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, 'n'); break;
        case '\t': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, 't'); break;
        case '\v': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, 'v'); break;
        case '\f': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, 'f'); break;
        case '\b': gate_strbuilder_append_chars(builder, 1, '\\'); gate_strbuilder_append_chars(builder, 1, 'b'); break;
        default: gate_strbuilder_append_chars(builder, 1, c); break;
        }

        ++ptr;
        --len;
    }
}

void gate_wasm_js_code_assign_string(gate_strbuilder_t* builder, gate_wasm_js_code_assign_enum_t assign_type, gate_string_t const* var_name, gate_string_t const* var_value)
{
    switch (assign_type)
    {
    case gate_wasm_js_code_assign_var: gate_strbuilder_append_cstr(builder, "var "); break;
    case gate_wasm_js_code_assign_let: gate_strbuilder_append_cstr(builder, "let "); break;
    default: break;
    }
    gate_strbuilder_append_string(builder, var_name);
    gate_strbuilder_append_cstr(builder, " = '");
    gate_wasm_js_encode_string(builder, var_value);
    gate_strbuilder_append_cstr(builder, "';\n");
}

void gate_wasm_js_code_assign_str(gate_strbuilder_t* builder, gate_wasm_js_code_assign_enum_t assign_type, char const* var_name, char const* var_value)
{
    gate_string_t name, value;
    gate_string_create_static(&name, var_name);
    gate_string_create_static(&value, var_value);
    gate_wasm_js_code_assign_string(builder, assign_type, &name, &value);
}

void gate_wasm_js_code_assign_str_string(gate_strbuilder_t* builder, gate_wasm_js_code_assign_enum_t assign_type, char const* var_name, gate_string_t const* var_value)
{
    gate_string_t name;
    gate_string_create_static(&name, var_name);
    gate_wasm_js_code_assign_string(builder, assign_type, &name, var_value);
}


static void gate_wasm_js_execute_impl(gate_string_t const* ptr_str)
{
    gate_cstrbuffer8_t buffer = GATE_INIT_EMPTY;
    char const* native_str = NULL;
    GATE_WASM_TRACE_STRING(ptr_str);
    gate_cstrbuffer_create_string(&buffer, ptr_str, false);
    native_str = gate_cstrbuffer_get(&buffer);
    emscripten_run_script(native_str);
    gate_cstrbuffer_destroy(&buffer);
}
static void gate_wasm_js_execute_runtime(int str_buffer, int str_ptr, int str_len)
{
    gate_string_t str;
    str.buffer = (gate_stringbuffer_t*)str_buffer;
    str.str = (char const*)str_ptr;
    str.length = (gate_size_t)str_len;

    gate_wasm_js_execute_impl(&str);
    gate_string_release(&str);
}
void gate_wasm_js_execute(gate_string_t const* js_code)
{
    GATE_WASM_TRACE("gate_wasm_js_execute()");
    if (gate_wasm_in_runtime_thread())
    {
        gate_wasm_js_execute_impl(js_code);
    }
    else
    {
        gate_string_t str = GATE_STRING_INIT_EMPTY;
        if (NULL != gate_string_clone(&str, js_code))
        {
            emscripten_wasm_worker_post_function_viii(0, &gate_wasm_js_execute_runtime,
                (int)str.buffer, (int)str.str, (int)str.length);
        }
    }
}


static void gate_wasm_js_execute_int_impl(gate_string_t const* ptr_str, int* ptr_int)
{
    int ret = 0;
    gate_cstrbuffer8_t buffer = GATE_INIT_EMPTY;
    char const* native_str = NULL;

    GATE_WASM_TRACE_STRING(ptr_str);
    gate_cstrbuffer_create_string(&buffer, ptr_str, false);

    native_str = gate_cstrbuffer_get(&buffer);

    ret = emscripten_run_script_int(native_str);

    gate_cstrbuffer_destroy(&buffer);

    if (ptr_int)
    {
        *ptr_int = ret;
    }
}
static void gate_wasm_js_execute_runtime_int(int int_ptr_js_code, int int_ptr_signal, int int_ptr_int)
{
    gate_string_t const* ptr_js_code = (gate_string_t const*)int_ptr_js_code;
    emscripten_semaphore_t* ptr_signal = (emscripten_semaphore_t*)int_ptr_signal;
    int* ptr_int = (int*)int_ptr_int;

    gate_wasm_js_execute_int_impl(ptr_js_code, ptr_int);
    emscripten_semaphore_release(ptr_signal, 1);
}
void gate_wasm_js_execute_int(gate_string_t const* js_code, int* ptr_int)
{
    GATE_WASM_TRACE("gate_wasm_js_execute_int()");
    if (gate_wasm_in_runtime_thread())
    {
        gate_wasm_js_execute_int_impl(js_code, ptr_int);
    }
    else
    {
        emscripten_semaphore_t signal = EMSCRIPTEN_SEMAPHORE_T_STATIC_INITIALIZER(0);
        emscripten_wasm_worker_post_function_viii(0, &gate_wasm_js_execute_runtime_int,
            (int)js_code, (int)&signal, (int)ptr_int);
        emscripten_semaphore_waitinf_acquire(&signal, 1);
    }
}





static void gate_wasm_js_execute_str_impl(gate_string_t const* ptr_js, gate_string_t* ptr_str_out)
{
    char const* ret = NULL;
    gate_cstrbuffer8_t buffer = GATE_INIT_EMPTY;

    GATE_WASM_TRACE_STRING(ptr_js);

    gate_cstrbuffer_create_string(&buffer, ptr_js, false);

    ret = emscripten_run_script_string(gate_cstrbuffer_get(&buffer));

    gate_cstrbuffer_destroy(&buffer);

    if (ptr_str_out)
    {
        gate_string_create(ptr_str_out, ret, gate_str_length(ret));
    }
}
static void gate_wasm_js_execute_runtime_str(int int_ptr_js_code, int int_ptr_signal, int int_ptr_str)
{
    gate_string_t const* ptr_js_code = (gate_string_t const*)int_ptr_js_code;
    emscripten_semaphore_t* ptr_signal = (emscripten_semaphore_t*)int_ptr_signal;
    gate_string_t* ptr_str = (gate_string_t*)int_ptr_str;

    gate_wasm_js_execute_str_impl(ptr_js_code, ptr_str);
    emscripten_semaphore_release(ptr_signal, 1);
}
void gate_wasm_js_execute_str(gate_string_t const* js_code, gate_string_t* ptr_str)
{
    GATE_WASM_TRACE("gate_wasm_js_execute_str()");

    if (gate_wasm_in_runtime_thread())
    {
        gate_wasm_js_execute_str_impl(js_code, ptr_str);
    }
    else
    {
        emscripten_semaphore_t signal = EMSCRIPTEN_SEMAPHORE_T_STATIC_INITIALIZER(0);
        emscripten_wasm_worker_post_function_viii(0, &gate_wasm_js_execute_runtime_str,
            (int)js_code, (int)&signal, (int)ptr_str);
        emscripten_semaphore_waitinf_acquire(&signal, 1);
    }
}



gate_bool_t gate_wasm_html_add_element(gate_string_t const* html_entity, gate_string_t const* html_id, gate_string_t const* html_parent_id,
    gate_string_t const* attrib_names, gate_string_t const* attrib_values, gate_size_t attribs_count)
{
    gate_bool_t ret = false;
    gate_strbuilder_t builder = GATE_INIT_EMPTY;
    gate_string_t js_code = GATE_STRING_INIT_EMPTY;

    do
    {

        GATE_WASM_TRACE("gate_wasm_html_add_element()");

        gate_strbuilder_create(&builder, 512);

        if (gate_string_is_empty(html_parent_id))
        {
            gate_strbuilder_append(&builder,
                GATE_PRINT_CSTR, "let parent = document.body;\n",
                GATE_PRINT_END);
        }
        else
        {
            gate_wasm_js_code_assign_str_string(&builder, gate_wasm_js_code_assign_let, "parent_id", html_parent_id);
            gate_strbuilder_append(&builder,
                GATE_PRINT_CSTR, "let parent = document.getElementById(parent_id);\n",
                GATE_PRINT_END);
        }

        gate_wasm_js_code_assign_str_string(&builder, gate_wasm_js_code_assign_let, "element_id", html_id);
        gate_wasm_js_code_assign_str_string(&builder, gate_wasm_js_code_assign_let, "html_entity", html_entity);
        gate_strbuilder_append_cstr(&builder,
            "let element = document.getElementById(element_id);\n"
            "if(null == element) {\n"
            "  element = document.createElement(html_entity);\n"
            "  element.id = element_id;\n"
            "  parent.appendChild(element);\n"
            "}\n"
        );

        while (attribs_count > 0)
        {
            gate_strbuilder_append_cstr(&builder, "element.setAttribute('");
            gate_strbuilder_append_string(&builder, attrib_names);
            gate_strbuilder_append_cstr(&builder, "', '");
            gate_wasm_js_encode_string(&builder, attrib_values);
            gate_strbuilder_append_cstr(&builder, "');\n");

            ++attrib_names;
            ++attrib_values;
            --attribs_count;
        }

        if (NULL != gate_strbuilder_to_string(&builder, &js_code))
        {
            gate_wasm_js_execute(&js_code);
            ret = true;
        }

    } while (0);

    gate_string_release(&js_code);
    gate_strbuilder_release(&builder);
    return ret;
}

gate_bool_t gate_wasm_html_set_element_attribs(gate_string_t const* html_id,
    gate_string_t const* attrib_names, gate_string_t const* attrib_values, gate_size_t attribs_count)
{
    gate_bool_t ret = false;
    gate_strbuilder_t builder = GATE_INIT_EMPTY;
    gate_string_t js_code = GATE_STRING_INIT_EMPTY;

    do
    {
        gate_strbuilder_create(&builder, 512);

        GATE_WASM_TRACE("gate_wasm_html_set_element_attribs()");

        gate_wasm_js_code_assign_str_string(&builder, gate_wasm_js_code_assign_let, "element_id", html_id);
        gate_strbuilder_append_cstr(&builder, "let element = document.getElementById(element_id);\n");

        while (attribs_count > 0)
        {
            gate_strbuilder_append_cstr(&builder, "element.setAttribute('");
            gate_strbuilder_append_string(&builder, attrib_names);
            gate_strbuilder_append_cstr(&builder, "', '");
            gate_wasm_js_encode_string(&builder, attrib_values);
            gate_strbuilder_append_cstr(&builder, "');\n");

            ++attrib_names;
            ++attrib_values;
            --attribs_count;
        }

        if (NULL != gate_strbuilder_to_string(&builder, &js_code))
        {
            gate_wasm_js_execute(&js_code);
            ret = true;
        }

    } while (0);

    gate_string_release(&js_code);
    gate_strbuilder_release(&builder);
    return ret;
}

gate_bool_t gate_wasm_html_get_element_attrib(gate_string_t const* html_id,
    gate_string_t const* attrib_name, gate_string_t* attrib_value)
{
    gate_bool_t ret = false;
    gate_strbuilder_t builder = GATE_INIT_EMPTY;
    gate_string_t js_code = GATE_STRING_INIT_EMPTY;

    do
    {
        if (!html_id || !attrib_name || !attrib_value)
        {
            break;
        }

        GATE_WASM_TRACE("gate_wasm_html_get_element_attrib()");

        gate_strbuilder_create(&builder, 512);

        gate_wasm_js_code_assign_str_string(&builder, gate_wasm_js_code_assign_let, "element_id", html_id);
        gate_strbuilder_append_cstr(&builder, "let element = document.getElementById(element_id);\n");
        gate_strbuilder_append_cstr(&builder, "return element.getAttribute('");
        gate_strbuilder_append_string(&builder, attrib_name);
        gate_strbuilder_append_cstr(&builder, "');\n");

        if (NULL != gate_strbuilder_to_string(&builder, &js_code))
        {
            gate_string_create_empty(attrib_value);
            gate_wasm_js_execute_str(&js_code, attrib_value);
            ret = true;
        }

    } while (0);

    gate_string_release(&js_code);
    gate_strbuilder_release(&builder);
    return ret;
}

gate_bool_t gate_wasm_html_set_element_props(gate_string_t const* html_id,
    gate_string_t const* prop_names, gate_string_t const* prop_values, gate_size_t props_count)
{
    gate_bool_t ret = false;
    gate_strbuilder_t builder = GATE_INIT_EMPTY;
    gate_string_t js_code = GATE_STRING_INIT_EMPTY;

    do
    {
        gate_strbuilder_create(&builder, 512);

        GATE_WASM_TRACE("gate_wasm_html_set_element_props()");

        gate_wasm_js_code_assign_str_string(&builder, gate_wasm_js_code_assign_let, "element_id", html_id);
        gate_strbuilder_append_cstr(&builder, "let element = document.getElementById(element_id);\n");

        while (props_count > 0)
        {
            gate_strbuilder_append_cstr(&builder, "element.");
            gate_strbuilder_append_string(&builder, prop_names);
            gate_strbuilder_append_cstr(&builder, " = '");
            gate_wasm_js_encode_string(&builder, prop_values);
            gate_strbuilder_append_cstr(&builder, "';\n");

            ++prop_names;
            ++prop_values;
            --props_count;
        }

        if (NULL != gate_strbuilder_to_string(&builder, &js_code))
        {
            gate_wasm_js_execute(&js_code);
            ret = true;
        }

    } while (0);

    gate_string_release(&js_code);
    gate_strbuilder_release(&builder);
    return ret;
}

gate_bool_t gate_wasm_html_get_element_props(gate_string_t const* html_id,
    gate_string_t const* prop_name, gate_string_t* prop_value)
{
    gate_bool_t ret = false;
    gate_strbuilder_t builder = GATE_INIT_EMPTY;
    gate_string_t js_code = GATE_STRING_INIT_EMPTY;

    do
    {
        if (!html_id || !prop_name || !prop_value)
        {
            break;
        }

        GATE_WASM_TRACE("gate_wasm_html_get_element_props()");

        gate_strbuilder_create(&builder, 512);

        gate_wasm_js_code_assign_str_string(&builder, gate_wasm_js_code_assign_let, "element_id", html_id);
        gate_strbuilder_append_cstr(&builder, "let element = document.getElementById(element_id);\n");
        gate_strbuilder_append_cstr(&builder, "return element.");
        gate_strbuilder_append_string(&builder, prop_name);
        gate_strbuilder_append_cstr(&builder, ";\n");

        if (NULL != gate_strbuilder_to_string(&builder, &js_code))
        {
            gate_string_create_empty(prop_value);
            gate_wasm_js_execute_str(&js_code, prop_value);
            ret = true;
        }

    } while (0);

    gate_string_release(&js_code);
    gate_strbuilder_release(&builder);
    return ret;
}



#endif /* GATE_SYS_WASM && GATE_COMPILER_EMSCRIPTEN */