bytecodealliance / wasm-micro-runtime

WebAssembly Micro Runtime (WAMR)
Apache License 2.0
4.8k stars 608 forks source link

Getting error "ASSERTION FAILED: gci_is_heap_valid(heap)" when call wasm_runtime_module_malloc() multiple times. #448

Closed JavanZhu closed 3 years ago

JavanZhu commented 3 years ago

Hello, I am following the tutorial pass-buffer-to-wasm-function to call wasm function and pass some string arguments to it from native, getting following error when call wasm_runtime_module_malloc() multiple times.

ASSERTION FAILED: gci_is_heap_valid(heap), at file wasm-micro-runtime/core/shared/mem-alloc/ems/ems_alloc.c, line 342

In ems_alloc.c, it looks like the values of variable heap->heap_id and heap is not equivalent.

/**
 * Do some checking to see if given pointer is a possible valid heap
 * @return GC_TRUE if all checking passed, GC_FALSE otherwise
 */
int
gci_is_heap_valid(gc_heap_t *heap)
{
    if (!heap)
        return GC_FALSE;
    if (heap->heap_id != (gc_handle_t) heap)
        return GC_FALSE;

    return GC_TRUE;
}

So my question is:

  1. How to solve it or Possible reasons for this error?
  2. The code location where the variable heap->heap_id is modified

please tell me something I'm missed, Thank you very much.

wenyongh commented 3 years ago

Hi, it seems that the heap structure is corrupted, not sure whether it is overwritten by your wasm app, or other codes e.g. wasm vm or your host embedder. What is the language of wasm source code, and what is the wasm compiler? Is there a simple way to reproduce the error?

And could you please ensure that the buffer applied from wasm_runtime_module_malloc is not overwritten? And also the native address of buffer applied might be changed after memory.grow opcode is executed, so please do not remember the native address for further use, if you want to do that, you can remember the app offset, and convert it to native address every time we use it.

If you want to debug, maybe you can watch the heap->heap_id in gdb to see when it was changed. And also you can enable the heap verify feature by changing BH_ENABLE_GC_VERIFY to 1 in file core/config.h to see whether the heap data is overwritten.

JavanZhu commented 3 years ago

Hi @wenyongh, thank you for your reply.

My ENVIRONMENT:

I reproduce the error through following step:

  1. my wasm source code (AssemblyScript), note that I pass some big strings to native runtime.
import * as console from "../wamr_app_lib/console";
import * as utils from "../wamr_app_lib/utils";

export declare type addr_t = i32; 

export function strToAB(str: string): ArrayBuffer {
  return String.UTF8.encode(str, true);
}

@external("env", "dispatch_native_call")
declare function dispatch_native_call(
  funcName: ArrayBuffer,
  params: ArrayBuffer
): void;

// main function of wasm app
export function onLoad(): void {
  let funcName = strToAB(`dispatch_native_call`);
  let big_param = strToAB(big_string);
  // call native method 
  dispatch_native_call(funcName, big_param);

  **// call native method again, it will throw error "ASSERTION FAILED: gci_is_heap_valid(heap)"
  let big_param2 = strToAB(big_string2);
  dispatch_native_call(funcName, big_param2);**

}

export function dispatch_native_event(
  buffer_offset: addr_t,
  size: i32
): void {
  console.log(
    "dispatch_native_event() called: buffer_offset = [" +
      buffer_offset.toString() +
      "], size = [" +
      size.toString() +
      "]"
  );

  var buffer = new ArrayBuffer(size);
  var dataview = new DataView(buffer);

  for (let i = 0; i < size; i++) {
    dataview.setUint8(i, load<i8>(buffer_offset + i, 0, 1));
  }

  var msg = String.UTF8.decode(buffer);
  console.log("dispatch_native_event: result = [" + msg + "]");
}

let big_string = `English literature, the body of written works produced in the English language by inhabitants of the British Isles (including Ireland) from the 7th century to the present day. The major literatures written in English outside the British Isles are treated separately under American literature, Australian literature, Canadian literature, and New Zealand literature.

George Gordon Byron, 6th Baron Byron. Lord Byron English poet (1788-1824) was a leading figure in the Romantic movement.
BRITANNICA QUIZ
10 British Poets: A Quiz
This quiz will test your knowledge of ten notable poets from Great Britain. Find out how much you know about their lives and works.
English literature has sometimes been stigmatized as insular. It can be argued that no single English novel attains the universality of the Russian writer Leo Tolstoy’s War and Peace or the French writer Gustave Flaubert’s Madame Bovary. Yet in the Middle Ages the Old English literature of the subjugated Saxons was leavened by the Latin and Anglo-Norman writings, eminently foreign in origin, in which the churchmen and the Norman conquerors expressed themselves. From this combination emerged a flexible and subtle linguistic instrument exploited by Geoffrey Chaucer and brought to supreme application by William Shakespeare. During the Renaissance the renewed interest in Classical learning and values had an important effect on English literature, as on all the arts; and ideas of Augustan literary propriety in the 18th century and reverence in the 19th century for a less specific, though still selectively viewed, Classical antiquity continued to shape the literature. All three of these impulses derived from a foreign source, namely the Mediterranean basin. The Decadents of the late 19th century and the Modernists of the early 20th looked to continental European individuals and movements for inspiration. Nor was attraction toward European intellectualism dead in the late 20th century, for by the mid-1980s the approach known as structuralism, a phenomenon predominantly French and German in origin, infused the very study of English literature itself in a host of published critical studies and university departments. Additional influence was exercised by deconstructionist analysis, based largely on the work of French philosopher Jacques Derrida.

Further, Britain’s past imperial activities around the globe continued to inspire literature—in some cases wistful, in other cases hostile. Finally, English literature has enjoyed a certain diffusion abroad, not only in predominantly English-speaking countries but also in all those others where English is the first choice of study as a second language.

English literature is therefore not so much insular as detached from the continental European tradition across the Channel. It is strong in all the conventional categories of the bookseller’s list: in Shakespeare it has a dramatist of world renown; in poetry, a genre notoriously resistant to adequate translation and therefore difficult to compare with the poetry of other literatures, it is so peculiarly rich as to merit inclusion in the front rank; English literature’s humour has been found as hard to convey to foreigners as poetry, if not more so—a fact at any rate permitting bestowal of the label “idiosyncratic”; English literature’s remarkable body of travel writings constitutes another counterthrust to the charge of insularity; in autobiography, biography, and historical writing, English literature compares with the best of any culture; and children’s literature, fantasy, essays, and journals, which tend to be considered minor genres, are all fields of exceptional achievement as regards English literature. Even in philosophical writings, popularly thought of as hard to combine with literary value, thinkers such as Thomas Hobbes, John Locke, David Hume, John Stuart Mill, and Bertrand Russell stand comparison for lucidity and grace with the best of the French philosophers and the masters of Classical antiquity.

Get exclusive access to content from our 1768 First Edition with your subscription.
Subscribe today
Some of English literature’s most distinguished practitioners in the 20th century—from Joseph Conrad at its beginning to V.S. Naipaul and Tom Stoppard at its end—were born outside the British Isles. What is more, none of the aforementioned had as much in common with his adoptive country as did, for instance, Doris Lessing and Peter Porter (two other distinguished writer-immigrants to Britain), both having been born into a British family and having been brought up on British Commonwealth soil.

On the other hand, during the same period in the 20th century, many notable practitioners of English literature left the British Isles to live abroad: James Joyce, D.H. Lawrence, Aldous Huxley, Christopher Isherwood, Robert Graves, Graham Greene, Muriel Spark, and Anthony Burgess. In one case, that of Samuel Beckett, this process was carried to the extent of writing works first in French and then translating them into English.

Even English literature considered purely as a product of the British Isles is extraordinarily heterogeneous, however. Literature actually written in those Celtic tongues once prevalent in Cornwall, Ireland, Scotland, and Wales—called the “Celtic Fringe”—is treated separately (see Celtic literature). Yet Irish, Scots, and Welsh writers have contributed enormously to English literature even when they have written in dialect, as the 18th-century poet Robert Burns and the 20th-century Scots writer Alasdair Gray have done. In the latter half of the 20th century, interest began also to focus on writings in English or English dialect by recent settlers in Britain, such as Afro-Caribbeans and people from Africa proper, the Indian subcontinent, and East Asia.

Even within England, culturally and historically the dominant partner in the union of territories comprising Britain, literature has been as enriched by strongly provincial writers as by metropolitan ones. Another contrast more fruitful than not for English letters has been that between social milieus, however much observers of Britain in their own writings may have deplored the survival of class distinctions. As far back as medieval times, a courtly tradition in literature cross-fertilized with an earthier demotic one. Shakespeare’s frequent juxtaposition of royalty in one scene with plebeians in the next reflects a very British way of looking at society. This awareness of differences between high life and low, a state of affairs fertile in creative tensions, is observable throughout the history of English literature.

Learn More!
English literature
KEY PEOPLE
Simon Armitage
David Walliams
Clemence Dane
William Shakespeare
John Milton
Samuel Johnson
Charles Dickens
William Blake
Winston Churchill
Virginia Woolf
RELATED TOPICS
United Kingdom
American literature
England
Canadian literature
Literature
Australian literature
Western literature
New Zealand literature
Cornish literature
Poet laureate
The Old English Period
Poetry
The Angles, Saxons, and Jutes who invaded Britain in the 5th and 6th centuries brought with them the common Germanic metre; but of their earliest oral poetry, probably used for panegyric, magic, and short narrative, little or none survives. For nearly a century after the conversion of King Aethelberht I of Kent to Christianity about 600, there is no evidence that the English wrote poetry in their own language. But St. Bede the Venerable, in his Historia ecclesiastica gentis Anglorum (“Ecclesiastical History of the English People”), wrote that in the late 7th century Caedmon, an illiterate Northumbrian cowherd, was inspired in a dream to compose a short hymn in praise of the creation. Caedmon later composed verses based on Scripture, which was expounded for him by monks at Streaneshalch (now called Whitby), but only the “Hymn of Creation” survives. Caedmon legitimized the native verse form by adapting it to Christian themes. Others, following his example, gave England a body of vernacular poetry unparalleled in Europe before the end of the 1st millennium.

Alliterative verse
Virtually all Old English poetry is written in a single metre, a four-stress line with a syntactical break, or caesura, between the second and third stresses, and with alliteration linking the two halves of the line; this pattern is occasionally varied by six-stress lines. The poetry is formulaic, drawing on a common set of stock phrases and phrase patterns, applying standard epithets to various classes of characters, and depicting scenery with such recurring images as the eagle and the wolf, which wait during battles to feast on carrion, and ice and snow, which appear in the landscape to signal sorrow. In the best poems such formulas, far from being tedious, give a strong impression of the richness of the cultural fund from which poets could draw. Other standard devices of this poetry are the kenning, a figurative name for a thing, usually expressed in a compound noun (e.g., swan-road used to name the sea); and variation, the repeating of a single idea in different words, with each repetition adding a new level of meaning. That these verse techniques changed little during 400 years of literary production suggests the extreme conservatism of Anglo-Saxon culture.

The major manuscripts
Most Old English poetry is preserved in four manuscripts of the late 10th and early 11th centuries. The Beowulf manuscript (British Library) contains Beowulf, Judith, and three prose tracts; the Exeter Book (Exeter Cathedral) is a miscellaneous gathering of lyrics, riddles, didactic poems, and religious narratives; the Junius Manuscript (Bodleian Library, Oxford)—also called the Caedmon Manuscript, even though its contents are no longer attributed to Caedmon—contains biblical paraphrases; and the Vercelli Book (found in the cathedral library in Vercelli, Italy) contains saints’ lives, several short religious poems, and prose homilies. In addition to the poems in these books are historical poems in the Anglo-Saxon Chronicle; poetic renderings of Psalms 51–150; the 31 “Metres” included in King Alfred the Great’s translation of Boethius’s De consolatione philosophiae (Consolation of Philosophy); magical, didactic, elegiac, and heroic poems; and others, miscellaneously interspersed with prose, jotted in margins, and even worked in stone or metal.

Problems of dating
Few poems can be dated as closely as Caedmon’s “Hymn.” King Alfred’s compositions fall into the late 9th century, and Bede composed his “Death Song” within 50 days of his death on May 25, 735. Historical poems such as “The Battle of Brunanburh” (after 937) and “The Battle of Maldon” (after 991) are fixed by the dates of the events they commemorate. A translation of one of Aldhelm’s riddles is found not only in the Exeter Book but also in an early 9th-century manuscript at Leiden, Neth. And at least a part of “The Dream of the Rood” can be dated by an excerpt carved on the 8th-century Ruthwell Cross (in Dumfriesshire, Scot.). But in the absence of such indications, Old English poems are hard to date, and the scholarly consensus that most were composed in the Midlands and the North in the 8th and 9th centuries gave way to uncertainty during the last two decades of the 20th century. Many now hold that “The Wanderer,” Beowulf, and other poems once assumed to have been written in the 8th century are of the 9th century or later. For most poems, there is no scholarly consensus beyond the belief that they were written between the 8th and the 11th centuries.

Religious verse
If few poems can be dated accurately, still fewer can be attributed to particular poets. The most important author from whom a considerable body of work survives is Cynewulf, who wove his runic signature into the epilogues of four poems. Aside from his name, little is known of him; he probably lived in the 9th century in Mercia or Northumbria. His works include The Fates of the Apostles, a short martyrology; The Ascension (also called Christ II), a homily and biblical narrative; Juliana, a saint’s passion set in the reign of the Roman emperor Maximian (late 3rd century CE); and Elene, perhaps the best of his poems, which describes the mission of St. Helena, mother of the emperor Constantine, to recover Christ’s cross. Cynewulf’s work is lucid and technically elegant; his theme is the continuing evangelical mission from the time of Christ to the triumph of Christianity under Constantine. Several poems not by Cynewulf are associated with him because of their subject matter. These include two lives of St. Guthlac and Andreas; the latter, the apocryphal story of how St. Andrew fell into the hands of the cannibalistic (and presumably mythical) Mermedonians, has stylistic affinities with Beowulf. Also in the “Cynewulf group” are several poems with Christ as their subject, of which the most important is “The Dream of the Rood,” in which the cross speaks of itself as Christ’s loyal thane and yet the instrument of his death. This tragic paradox echoes a recurring theme of secular poetry and at the same time movingly expresses the religious paradoxes of Christ’s triumph in death and humankind’s redemption from sin.

Several poems of the Junius Manuscript are based on the Old Testament narratives Genesis, Exodus, and Daniel. Of these, Exodus is remarkable for its intricate diction and bold imagery. The fragmentary Judith of the Beowulf Manuscript stirringly embellishes the story from the Apocrypha of the heroine who led the Jews to victory over the Assyrians.

Elegiac and heroic verse
The term elegy is used of Old English poems that lament the loss of worldly goods, glory, or human companionship. “The Wanderer” is narrated by a man, deprived of lord and kinsmen, whose journeys lead him to the realization that there is stability only in heaven. “The Seafarer” is similar, but its journey motif more explicitly symbolizes the speaker’s spiritual yearnings. Several others have similar themes, and three elegies—“The Husband’s Message,” “The Wife’s Lament,” and “Wulf and Eadwacer”—describe what appears to be a conventional situation: the separation of husband and wife by the husband’s exile.

“Deor” bridges the gap between the elegy and the heroic poem, for in it a poet laments the loss of his position at court by alluding to sorrowful stories from Germanic legend. Beowulf itself narrates the battles of Beowulf, a prince of the Geats (a tribe in what is now southern Sweden), against the monstrous Grendel, Grendel’s mother, and a fire-breathing dragon. The account contains some of the best elegiac verse in the language, and, by setting marvelous tales against a historical background in which victory is always temporary and strife is always renewed, the poet gives the whole an elegiac cast. Beowulf also is one of the best religious poems, not only because of its explicitly Christian passages but also because Beowulf’s monstrous foes are depicted as God’s enemies and Beowulf himself as God’s champion. Other heroic narratives are fragmentary. Of “The Battle of Finnsburh” and “Waldere” only enough remains to indicate that, when whole, they must have been fast-paced and stirring.

Of several poems dealing with English history and preserved in the Anglo-Saxon Chronicle, the most notable is “The Battle of Brunanburh,” a panegyric on the occasion of King Athelstan’s victory over a coalition of Norsemen and Scots in 937. But the best historical poem is not from the Anglo-Saxon Chronicle. “The Battle of Maldon,” which describes the defeat of Aldorman Byrhtnoth and much of his army at the hands of Viking invaders in 991, discovers in defeat an occasion to celebrate the heroic ideal, contrasting the determination of many of Byrhtnoth’s thanes to avenge his death or die in the attempt with the cowardice of others who left the field. Minor poetic genres include catalogs (two sets of “Maxims” and “Widsith,” a list of rulers, tribes, and notables in the heroic age), dialogues, metrical prefaces and epilogues to prose works of the Alfredian period, and liturgical poems associated with the Benedictine Office.

Learn More!
SIMILAR TOPICS
French literature
African literature
Arabic literature
Italian literature
German literature
Spanish literature
Japanese literature
Latin American literature
Chinese literature
Yiddish literature
Prose
The earliest English prose work, the law code of King Aethelberht I of Kent, was written within a few years of the arrival in England (597) of St. Augustine of Canterbury. Other 7th- and 8th-century prose, similarly practical in character, includes more laws, wills, and charters. According to Cuthbert, who was a monk at Jarrow, Bede at the time of his death had just finished a translation of the Gospel of St. John, though this does not survive. Two medical tracts, Herbarium and Medicina de quadrupedibus, very likely date from the 8th century.

Beginning of the old English poem, Beowulf, believed to have been composed between 700 and 750. (Old English literature)
BRITANNICA QUIZ
Poets and Poetry (Part Two) Quiz
Do you know which ancient Roman poet wrote Metamorphoses? Who wrote poetry to a woman named Laura? Test the outer reaches of what you know about poets and their poetry with this quiz.
Early translations into English
The earliest literary prose dates from the late 9th century, when King Alfred, eager to improve the state of English learning, led a vigorous program to translate into English “certain books that are necessary for all men to know.” Alfred himself translated the Pastoral Care of St. Gregory I the Great, the Consolation of Philosophy of Boethius, the Soliloquies of St. Augustine of Hippo, and the first 50 Psalms. His Pastoral Care is a fairly literal translation, but his Boethius is extensively restructured and revised to make explicit the Christian message that medieval commentators saw in that work. He revised the Soliloquies even more radically, departing from his source to draw from Gregory and St. Jerome, as well as from other works by Augustine. Alfred’s prefaces to these works are of great historical interest.

At Alfred’s urging, Bishop Werferth of Worcester translated the Dialogues of Gregory; probably Alfred also inspired anonymous scholars to translate Bede’s Historia ecclesiastica and Paulus Orosius’s Historiarum adversum paganos libri vii (Seven Books of History Against the Pagans). Both of these works are much abridged; the Bede translation follows its source slavishly, but the translator of Orosius added many details of northern European geography and also accounts of the voyages of Ohthere the Norwegian and Wulfstan the Dane. These accounts, in addition to their geographical interest, show that friendly commerce between England and Scandinavia was possible even during the Danish wars. The Anglo-Saxon Chronicle probably originated in Alfred’s reign. Its earliest annals (beginning in the reign of Julius Caesar) are laconic, except the entry for 755, which records in detail a feud between the West Saxon king Cynewulf and the would-be usurper Cyneheard. The entries covering the Danish wars of the late 9th century are much fuller, and those running from the reign of Ethelred II to the Norman Conquest in 1066 (when the Anglo-Saxon Chronicle exists in several versions) contain many passages of excellent writing. The early 10th century is not notable for literary production, but some of the homilies in the Vercelli Book and the Blickling Manuscript (Scheide Library, Princeton University) may belong to that period.

Late 10th- and 11th-century prose
The prose literature of the mid- to late 10th century is associated with the Benedictine Reform, a movement that sought to impose order and discipline on a monastic establishment that was thought to have grown lax. Aethelwold, bishop of Winchester and one of the leaders of the reform, translated the Rule of St. Benedict. But the greatest and most prolific writer of this period was his pupil Aelfric, a monk at Cerne and later abbot of Eynsham, whose works include three cycles of 40 homilies each (Catholic Homilies, 2 vol., and the Lives of the Saints), as well as homilies not in these cycles; a Latin grammar; a treatise on time and natural history; pastoral letters; and several translations. His Latin Colloquy, supplied with an Old English version by an anonymous glossarist, gives a fascinating glimpse into the Anglo-Saxon monastic classroom. Aelfric wrote with lucidity and astonishing beauty, using the rhetorical devices of Latin literature frequently but without ostentation; his later alliterative prose, which loosely imitates the rhythms of Old English poetry, influenced writers long after the Norman Conquest. Wulfstan, archbishop of York, wrote legal codes, both civil and ecclesiastical, and a number of homilies, including Sermo Lupi ad Anglos (“Wulf’s Address to the English”), a ferocious denunciation of the morals of his time. To judge from the number of extant manuscripts, these two writers were enormously popular. Byrhtferth of Ramsey wrote several Latin works and the Enchiridion, a textbook on the calendar, notable for its ornate style. Numerous anonymous works, some of very high quality, were produced in this period, including homilies, saints’ lives, dialogues, and translations of such works as the Gospels, several Old Testament books, liturgical texts, monastic rules, penitential handbooks, and the romance Apollonius of Tyre (translated from Latin but probably derived from a Greek original). The works of the Benedictine Reform were written during a few remarkable decades around the turn of the millennium. Little original work can be securely dated to the period after Wulfstan’s death (1023), but the continued vigour of the Anglo-Saxon Chronicle shows that good Old English prose was written right up to the Norman Conquest. By the end of this period, English had been established as a literary language with a polish and versatility unequaled among European vernaculars.

Learn More!
The Early Middle English Period
Poetry
The Norman Conquest worked no immediate transformation on either the language or the literature of the English. Older poetry continued to be copied during the last half of the 11th century; two poems of the early 12th century—“Durham,” which praises that city’s cathedral and its relics, and “Instructions for Christians,” a didactic piece—show that correct alliterative verse could be composed well after 1066. But even before the conquest, rhyme had begun to supplant rather than supplement alliteration in some poems, which continued to use the older four-stress line, although their rhythms varied from the set types used in classical Old English verse. A postconquest example is “The Grave,” which contains several rhyming lines; a poem from the Anglo-Saxon Chronicle on the death of William the Conqueror, lamenting his cruelty and greed, has more rhyme than alliteration.

England
READ MORE ON THIS TOPIC
England: Literature
In its literature, England arguably has attained its most influential cultural expression. For more than a millennium, each stage in the...
Influence of French poetry
By the end of the 12th century, English poetry had been so heavily influenced by French models that such a work as the long epic Brut (c. 1200) by Lawamon, a Worcestershire priest, seems archaic for mixing alliterative lines with rhyming couplets while generally eschewing French vocabulary. The Brut draws mainly upon Wace’s Anglo-Norman Roman de Brut (1155; based in turn upon Geoffrey of Monmouth’s Historia regum Britanniae [History of the Kings of Britain]), but in Lawamon’s hands the Arthurian story takes on a Germanic and heroic flavour largely missing in Wace. The Brut exists in two manuscripts, one written shortly after 1200 and the other some 50 years later. That the later version has been extensively modernized and somewhat abridged suggests the speed with which English language and literary tastes were changing in this period. The Proverbs of Alfred was written somewhat earlier, in the late 12th century; these proverbs deliver conventional wisdom in a mixture of rhymed couplets and alliterative lines, and it is hardly likely that any of the material they contain actually originated with the king whose wisdom they celebrate. The early 13th-century Bestiary mixes alliterative lines, three- and four-stress couplets, and septenary (heptameter) lines, but the logic behind this mix is more obvious than in the Brut and the Proverbs, for the poet was imitating the varied metres of his Latin source. More regular in form than these poems is the anonymous Poema morale in septenary couplets, in which an old man delivers a dose of moral advice to his presumably younger audience.

By far the most brilliant poem of this period is The Owl and the Nightingale (written after 1189), an example of the popular debate genre. The two birds argue topics ranging from their hygienic habits, looks, and songs to marriage, prognostication, and the proper modes of worship. The nightingale stands for the joyous aspects of life, the owl for the sombre; there is no clear winner, but the debate ends as the birds go off to state their cases to one Nicholas of Guildford, a wise man. The poem is learned in the clerical tradition but wears its learning lightly as the disputants speak in colloquial and sometimes earthy language. Like the Poema morale, The Owl and the Nightingale is metrically regular (octosyllabic couplets), but it uses the French metre with an assurance unusual in so early a poem.

Didactic poetry
The 13th century saw a rise in the popularity of long didactic poems presenting biblical narrative, saints’ lives, or moral instruction for those untutored in Latin or French. The most idiosyncratic of these is the Ormulum by Orm, an Augustinian canon in the north of England. Written in some 20,000 lines arranged in unrhymed but metrically rigid couplets, the work is interesting mainly in that the manuscript that preserves it is Orm’s autograph and shows his somewhat fussy efforts to reform and regularize English spelling. Other biblical paraphrases are Genesis and Exodus, Jacob and Joseph, and the vast Cursor mundi, whose subject, as its title suggests, is the history of the world. An especially popular work was the South English Legendary, which began as a miscellaneous collection of saints’ lives but was expanded by later redactors and rearranged in the order of the church calendar. The didactic tradition continued into the 14th century with Robert Mannyng’s Handling Sin, a confessional manual whose expected dryness is relieved by the insertion of lively narratives, and the Prick of Conscience, a popular summary of theology sometimes attributed to the mystic Richard Rolle.

Verse romance
The earliest examples of verse romance, a genre that would remain popular through the Middle Ages, appeared in the 13th century. King Horn and Floris and Blauncheflour both are preserved in a manuscript of about 1250. King Horn, oddly written in short two- and three-stress lines, is a vigorous tale of a kingdom lost and regained, with a subplot concerning Horn’s love for Princess Rymenhild. Floris and Blauncheflour is more exotic, being the tale of a pair of royal lovers who become separated and, after various adventures in eastern lands, reunited. Not much later than these is The Lay of Havelok the Dane, a tale of princely love and adventure similar to King Horn but more competently executed. Many more such romances were produced in the 14th century. Popular subgenres were “the matter of Britain” (Arthurian romances such as Of Arthour and of Merlin and Ywain and Gawain), “the matter of Troy” (tales of antiquity such as The Siege of Troy and King Alisaunder), and the English Breton lays (stories of otherworldly magic, such as Lai le Freine and Sir Orfeo, modeled after those of professional Breton storytellers). These relatively unsophisticated works were written for a bourgeois audience, and the manuscripts that preserve them are early examples of commercial book production. The humorous beast epic makes its first appearance in Britain in the 13th century with The Fox and the Wolf, taken indirectly from the Old French Roman de Renart. In the same manuscript with this work is Dame Sirith, the earliest English fabliau. Another sort of humour is found in The Land of Cockaygne, which depicts a utopia better than heaven, where rivers run with milk, honey, and wine, geese fly about already roasted, and monks hunt with hawks and dance with nuns.

Learn More!
The lyric`

let big_string2 = `The lyric was virtually unknown to Old English poets. Poems such as “Deor” and “Wulf and Eadwacer,” which have been called lyrics, are thematically different from those that began to circulate orally in the 12th century and to be written down in great numbers in the 13th; these Old English poems also have a stronger narrative component than the later productions. The most frequent topics in the Middle English secular lyric are springtime and romantic love; many rework such themes tediously, but some, such as “Foweles in the frith” (13th century) and “Ich am of Irlaunde” (14th century), convey strong emotions in a few lines. Two lyrics of the early 13th century, “Mirie it is while sumer ilast” and “Sumer is icumen in,” are preserved with musical settings, and probably most of the others were meant to be sung. The dominant mood of the religious lyrics is passionate: the poets sorrow for Christ on the cross and for the Virgin Mary, celebrate the “five joys” of Mary, and import language from love poetry to express religious devotion. Excellent early examples are “Nou goth sonne under wod” and “Stond wel, moder, ounder rode.” Many of the lyrics are preserved in manuscript anthologies, of which the best is British Library manuscript Harley 2253 from the early 14th century. In this collection, known as the Harley Lyrics, the love poems, such as “Alysoun” and “Blow, Northern Wind,” take after the poems of the Provençal troubadours but are less formal, less abstract, and more lively. The religious lyrics also are of high quality; but the most remarkable of the Harley Lyrics, “The Man in the Moon,” far from being about love or religion, imagines the man in the Moon as a simple peasant, sympathizes with his hard life, and offers him some useful advice on how to best the village hayward (a local officer in charge of a town’s common herd of cattle).

A poem such as “The Man in the Moon” serves as a reminder that, although the poetry of the early Middle English period was increasingly influenced by the Anglo-Norman literature produced for the courts, it is seldom “courtly.” Most English poets, whether writing about kings or peasants, looked at life from a bourgeois perspective. If their work sometimes lacks sophistication, it nevertheless has a vitality that comes from preoccupation with daily affairs.`
  1. modified wasm-micro-runtime/product-mini/platforms/darwin/main.c

void
call_wasm_func(struct WASMModuleInstanceCommon *module_inst,
               wasm_exec_env_t exec_env,
               char *param,
               uint32_t param_size)
{
    printf("call_wasm_func: param = [%s], param_size = [%d]\n", param,
           param_size);
    void *buffer = NULL;
    uint32_t buffer_for_wasm;
    wasm_function_inst_t func;
    char *func_name = "dispatch_native_event";

    if (!(func = wasm_runtime_lookup_function(module_inst, func_name,
                                              "(i32i32)"))) {
        printf("call_wasm_func: The wasm function [%s] "
               "is not found.\n",
               func_name);
        return;
    }

    buffer_for_wasm =
      wasm_runtime_module_malloc(module_inst, param_size, &buffer);
    if (buffer_for_wasm == 0) {
        printf("call_wasm_func: wasm_runtime_module_malloc failed, "
               "exception = [%s]\n",
               wasm_get_exception(module_inst));
        return;
    }

    uint32_t argv[2];
    strncpy(buffer, param,
            param_size); /* use native address for accessing in runtime */
    argv[0] = buffer_for_wasm; /* pass the buffer address for WASM space */
    argv[1] = param_size;      /* the size of buffer */
    if (!wasm_runtime_call_wasm(exec_env, func, 2, argv)) {
        printf("call_wasm_func: call wasm_runtime_call_wasm() failed: "
               "func_param = [%s], func_param_size = [%d], exception = [%s]",
               param, param_size, wasm_get_exception(module_inst));
        return;
    }
    wasm_runtime_module_free(module_inst, buffer_for_wasm);
    printf("call_wasm_func: finish\n");
}

// native method call by AssemblyScript
void
dispatch_native_call_wrapper(wasm_exec_env_t exec_env,
                             char *func_name,
                             char *func_param)
{
    printf("dispatch_native_call_wrapper() called with: func_name = [%s], "
           "param = [%s]\n",
           func_name, func_param);
    call_wasm_func(get_module_inst(exec_env), exec_env, "response from native",
                   sizeof("response from native"));
}

void
register_native_cb()
{
    static NativeSymbol native_symbols_env[] = {
      EXPORT_WASM_API_WITH_SIG2(dispatch_native_call, "($$)"),
    };

    if (!wasm_runtime_register_natives("env", native_symbols_env,
                                       sizeof(native_symbols_env)
                                       / sizeof(NativeSymbol))) {
        printf("register env module failed");
        wasm_runtime_destroy();
        return;
    }
}
...
int main(int argc, char *argv[])
{
    char *wasm_file = NULL;
    const char *func_name = NULL;
    uint8 *wasm_file_buf = NULL;
    uint32 wasm_file_size;
    uint32 stack_size = 20 * 1024 * 1024, heap_size = 20 * 1024 * 1024;
    wasm_module_t wasm_module = NULL;

    ....

    /* initialize runtime environment */
    if (!wasm_runtime_full_init(&init_args)) {
        printf("Init runtime environment failed.\n");
        return -1;
    }

    register_native_cb();

    bh_log_set_verbose_level(log_verbose_level);

    ...
}
  1. when run following command, it will crash and throw error "ASSERTION FAILED: gci_is_heap_valid(heap), at file **wasm-micro-runtime/core/shared/mem-alloc/ems/ems_alloc.c, line 337"
    ./iwasm -f onLoad ../invalid_heap_res/debug_big_str.wasm
JavanZhu commented 3 years ago

@wenyongh After i updated wasm-micro-runtime source code to the latest commit: 20201126103200 and execute the debug_big_str.wasm again, I got error

Exception: out of memory

Because it run in following code. 20201126105310

I hope this information is helpful, please tell me if you need more information about this problem, thank you.

wenyongh commented 3 years ago

@JavanZhu yes, in latest version, we move the app heap structure (header part) out of linear memory, so only app heap data pool is inside the linear memory, and also we add many checks for the heap data nodes to enhance the security. If we find that the heap data pool is corrupted, we just report error and do nothing in the app heap memory allocation/free.

The app heap is inserted or appended into the linear memory, and the __heap_base global exported or initial page count of wasm app is amended, for most compilers, this works. For your application, we found that the wasm bytecode stores data to linear memory from low address to high address, like that it initializes the whole linear memory except the data area, so it makes app heap corrupted.

And we found that it exports the memory allocation/free functions: alloc, retain and release. I have a test, by using the functions instead of alloc/free memory from/to app heap, you wasm app works well. I updated the patch, could you please have a try? This is a temporary solution, we might change the behavior of module_malloc/module_free in the future: if alloc/retain/release functions are found, we don't create the app heap any more, we can just call these functions to alloc/free memory from/to linear memory.

Note that you need to run iwasm with --heap-size=0 to disable the app heap:

iwasm --heap-size=0 -f onLoad debug_big_str.wasm

wamr_as.zip

JavanZhu commented 3 years ago

Hi @wenyongh, thank you for your help and detail explanation, thank you very much. I have tested it, and it works well if we pass string like "response from native", but if you replace it with other string like "{response from native"( just add a symbol "{" to it), and it throws following error:

wasm-micro-runtime/core/iwasm/interpreter/wasm_interp_classic.c, line 3381, meet an exception Exception: unreachable

I reproduced the above error by modified following code.

// native method call by AssemblyScript
void
dispatch_native_call_wrapper(wasm_exec_env_t exec_env,
                             char *func_name,
                             char *func_param)
{
    printf("dispatch_native_call_wrapper() called with: func_name = [%s], "
           "param = [%s]\n",
           func_name, func_param);

 //    call_wasm_func(get_module_inst(exec_env), exec_env, "{response from native",
//                   sizeof("response from native"));
      // following code will throw "Exception: unreachable" error
    call_wasm_func(get_module_inst(exec_env), exec_env, "{\"resCode\":0,\"resMsg\":\"Success\",\"data\":{\"varType1\":\"var content\",\"varType2\":\"var content\"}}",
                   sizeof("{\"resCode\":0,\"resMsg\":\"Success\",\"data\":{\"varType1\":\"var content\",\"varType2\":\"var content\"}}"));

}

ps: my wasm app(AssemblyScript) is compiled by AssemblyScript,

wenyongh commented 3 years ago

@JavanZhu welcome. I checked the bytecode of wasm app again and found that I wrongly understood the function argument of retain and release function. When calling these two functions, we can just pass the offset returned from __alloc, and no need to plus 16, so please change

argv[0] = offset + 16;
to
argv[0] = offset;

in two places. I tested again, it works well.

JavanZhu commented 3 years ago

@JavanZhu welcome. I checked the bytecode of wasm app again and found that I wrongly understood the function argument of retain and release function. When calling these two functions, we can just pass the offset returned from __alloc, and no need to plus 16, so please change

argv[0] = offset + 16;
to
argv[0] = offset;

in two places. I tested again, it works well.

@wenyongh yes, it works, thank you very much.

By the way, when i updated AssemblyScript compiler of my native environment from 0.14.12 to Version 0.17.3, I noticed that export functions is changed to following functions

 (export "memory" (memory $0))
 (export "__new" (func $~lib/rt/pure/__new))
 (export "__renew" (func $~lib/rt/pure/__renew))
 (export "__retain" (func $~lib/rt/pure/__retain))
 (export "__release" (func $~lib/rt/pure/__release))

just change "alloc" to "new", and everything work very well. Thank you for your help.

JavanZhu commented 3 years ago

@JavanZhu yes, in latest version, we move the app heap structure (header part) out of linear memory, so only app heap data pool is inside the linear memory, and also we add many checks for the heap data nodes to enhance the security. If we find that the heap data pool is corrupted, we just report error and do nothing in the app heap memory allocation/free.

The app heap is inserted or appended into the linear memory, and the __heap_base global exported or initial page count of wasm app is amended, for most compilers, this works. For your application, we found that the wasm bytecode stores data to linear memory from low address to high address, like that it initializes the whole linear memory except the data area, so it makes app heap corrupted.

And we found that it exports the memory allocation/free functions: alloc, retain and release. I have a test, by using the functions instead of alloc/free memory from/to app heap, you wasm app works well. I updated the patch, could you please have a try? This is a temporary solution, we might change the behavior of module_malloc/module_free in the future: if alloc/retain/release functions are found, we don't create the app heap any more, we can just call these functions to alloc/free memory from/to linear memory.

Note that you need to run iwasm with --heap-size=0 to disable the app heap:

iwasm --heap-size=0 -f onLoad debug_big_str.wasm

wamr_as.zip

@wenyongh I notice that you say "Note that you need to run iwasm with --heap-size=0 to disable the app heap:", it means that I should set the parameter heap_size of wasm_runtime_instantiate() to 0. but it works if I am not set heap_size to 0. So could you please give me more detail information about the reason why set heap_size to 0? thank you.

I will close this issue later.

    /* instantiate the module */
    if (!(wasm_module_inst = wasm_runtime_instantiate(wasm_module,
                                                      stack_size,
                                                      heap_size,
                                                      error_buf,
                                                      sizeof(error_buf)))) {
wenyongh commented 3 years ago

Hi, from the test, if app heap is enabled, it will be corrupted by your wasm application, and wasm_runtime_module_malloc/module_free will report error if runtime detects the corruption, and not sure whether this causes unexpected behavior for your application. Currently some wasi related environment variables are allocated from app heap, so module_malloc and module_free are called if app heap is enabled. We will try to fix it in the future, allocate these variables from global heap (or system memory) but not app heap, so you don't need to disable app heap again since it isn't actually used.